Search code examples
javastaticsynchronizationsingletonvolatile

Singleton instance instantiation


I am starting to get used to the keywords static and volatile in Java. In regards to a singleton class I am building, why do I see the following design?

public class Singleton{
    private static volatile Singleton _instance; 

    public static Singleton getInstance(){

       if(_instance == null){
           synchronized(Singleton.class){
               if(_instance == null)
                   _instance = new Singleton();
           }

       }
       return _instance;

    }
}

instead of this one?

public class Singleton{ 
    private static volatile Singleton _instance = new Singleton();

    public static Singleton getInstance(){
        return _instance;
    }
}

Does the first design have any advantage over the second? The only advantage I can see is that the second design synchronizes the whole method, which can require blocking the whole method. But my counter-thought to that is that the method is only one line and wouldn't block noticeably at all, right?


Solution

  • I would have preferred to add a comment but it seems I am not allowed to do that quite yet.

    The first example is Double-checked locking, which is no longer broken in Java:

    As of J2SE 5.0, this problem has been fixed. The volatile keyword now ensures that multiple threads handle the singleton instance correctly. ~ http://en.wikipedia.org/wiki/Double-checked_locking

    The Idea of Double-checked locking is to hold off on creating the singleton object until it is needed, and to lock the object with synchronized as little as possible.

    The second example would create the singleton as soon as the class was loaded (probably at start-up), regardless of whether it was ever used.

    Both examples are thread-safe, and as of J2SE 5.0 perfectly usable. It just depends on then you want to take the cost of creating the singleton object, and weather holding a object in memory that never gets used is acceptable.