In two previous posts I have tried to convince you not to implement the Singleton at all and to give up implementing it with lazy initialisation. Today I show how to write a singleton that uses lazy initialization. The presented code is one of 3 possible versions – the most readable one. Others will be shown in upcoming posts.

As with everything else in life there is a trade-off for the lazy initialization: either you loose the readability of the code or decrease the performance. Today we choose the latter one. Without further ado see the following snippet:

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
public class Singleton {
    private static Singleton INSTANCE = null;

    // Remember that Singleton constructor should be private
    private Singleton() {}

    private static Singleton createInstance() {
       Singleton singleton = new Singleton();
      //Initialization of the singleton here
      return singleton;
    }

    public static synchronized Singleton getSingleton() {
      if (INSTANCE == null) {
        INSTANCE = createInstance();
      }
      return INSTANCE;
    }
}

As you can see we finally have the lazy-initialization. Because we assume that our singleton can be accessed by many threads we need to synchronize the getSingleton(). You can see that the code is well readable, very similar to the one shown previously. So where is the performance impact?

The problem is in synchronization – unfortunately it’s not free. Notice that every time someone wants to get access to the singleton he has to wait on getSingleton() for other thread to exit. Even if no other thread is working the synchronization itself takes lots of time.

The only question remains: do you really care about that performance decrease? Not always – it depends on what your singleton does. If it handle heavy tasks (eg. query execution) or is not accessed very often than probably you won’t even notice. The only way this can hit you if the getSingleton() is executed heavily and the usage of the singleton is very short. That does not happen often in real life :)

To summarise: if you need lazy initialization there is a huge chance that the snippet shown above is exactly what you need. It is much better to have a readable code than try to optimize every irrelevant bit of your program. Still, if you’re 100% sure you need to have getSingleton() working fast then read one of the next posts where I will show you how to get it done (unfortunately by losing code readability).