In one of the recent posts I was trying to convince everyone not to create singletons. For those who still are not convinced I show today how to write it in a simplest and safest way possible. The following code base on one assumption: you do not need lazy initialization.

The idea behind lazy initialization is that the creation of the singleton object may be expensive and therefore we want to perform it only if we are about to use the singleton. This way we can save some time (assuming that in a given run singleton is not used) and memory (we keep some free mem before the first usage). But then the question arises: how often do you need that?

In my experience most of the singletons are either small objects that we expect to use often and therefore want to save memory by having only one instance of it (like ‘empty node’ or enum values) or large objects managing system resources (connection pool, database access) that are used very often in the code. In both of those cases you do not really benefit from lazy initialization.

Why am I convincing you to drop lazy initialization? Because in 95% of examples it is used only because the programmer wanted his code to look more fancy (pattern fever!). Without it the singleton code is really simple and really safe. (By safe I mean mostly coder-safe: that only a drunk junior developer could get the idea to ‘fix it’ and introduce something nasty). The code is following:

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
public class Singleton {
    private static final Singleton INSTANCE = createInstance();

    // 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 Singleton getSingleton() {
      return INSTANCE;
    }
}

Obviously we assume that any instance method of Singleton is properly synchronized and that it does not have a user-visible state. Some things to notice in this snippet:

  • It is important to have the constructor private – otherwise users of the class may start ignoring your getSingleton() and start creating the singletons on their own.
  • The reference INSTANCE to the singleton object is final. Thanks to that you have the guarantee that no one will swap this instance with for example a test one.
  • Because the getSingleton() just returns a constant reference it is thread safe and you do not have to synchronize it.

The code above is the easiest possible implementation. For those who still insist on using lazy initialization in one of the next posts I will show another way of implementing singleton pattern to include that.