~ read.

Thread safe singleton in Java

When we think about signleton, we think about something similar to this :

public class OurClass {

    private static OurClass _instance;

    public static synchronized OurClass getInstance() {
        if (_instance == null) {
            _instance = new OurClass();
        }
        return _instance;
    }

But there's this synchronized word that makes code a bit slower. Before i thought that this is the most common method of singleton creation - so called Lazy initialisation .But not so long time i found another way of Singleton creation, which i find also nice and interesting. This method is known as Initialization-on-demand holder idiom and it looks like this :

public class OurClass {
    private static class Holder {
        static final OurClass INSTANCE = new OurClass();
    }

    public static OurClass getInstance() {
        return Holder.INSTANCE;
    }
    // rest of class omitted
}

This code initializes the instance on the first calling of getInstance(), and importantly dosen't need synchronization because of the contract of the class loader:

  • the class loader loads classes when they are first accessed (in this case Holder's only access is within the getInstance()` method)
  • when a class is loaded, and before anyone can use it, all static initializers are guaranteed to be executed (that's when Holder's static block fires)
  • the class loader has its own synchronization built right in that make the above two points guaranteed to be threadsafe
    You also get the bonus of a final instance, even thought it's created lazily. Also note how clean and simple the code is.

I hope you will find it helpful for yourself just as i do.

comments powered by Disqus
comments powered by Disqus