Alex Rivera | Logout

Thread safety in Singleton

Asked 2010-05-26T11:04:55.743
15

I understand that double locking in Java is broken, so what are the best ways to make Singletons Thread Safe in Java? The first thing that springs to my mind is:

class Singleton{
    private static Singleton instance;

    private Singleton(){}

    public static synchronized Singleton getInstance(){
        if(instance == null) instance = new Singleton();
        return instance;
    }
}

Does this work? if so, is it the best way (I guess that depends on circumstances, so stating when a particular technique is best, would be useful)

Edit
Report

2 Answers

5

My preference is to just do:

class Singleton {
    private static final INSTANCE = new Singleton();

    private Singleton(){}

    public Singleton instance(){
        return INSTANCE;
    }
 }

It is rare that you need lazy initialization. You should always start with eager initialization and only change to lazy initialization if you see problems. Unless you have measured and pinpointed Singleton instantiation as the culprit of performance problem, just use eager initialization. It's simpler and more performant.

You could use enum for sure, but personally I don't bother because the benefit over normal eager instantiation is security (against reflection attack), and most of the time my code is vulnerable to such attacks anyways :p

answered 2010-05-26T12:26:24.783
1

You can use this snippet of code from wiki

public class Singleton {
   // Private constructor prevents instantiation from other classes
   private Singleton() {}

   /**
    * SingletonHolder is loaded on the first execution of Singleton.getInstance() 
    * or the first access to SingletonHolder.INSTANCE, not before.
    */
   private static class SingletonHolder { 
     private static final Singleton INSTANCE = new Singleton();
   }

   public static Singleton getInstance() {
     return SingletonHolder.INSTANCE;
   }
 }
answered 2010-05-26T13:29:40.633

Your Answer