singleton and public static variable Java

Achow picture Achow · Dec 5, 2012 · Viewed 12.7k times · Source

I have 2 options:

  1. Singleton Pattern

    class Singleton{
        private static Singleton singleton = null;
    
        public static synchronized Singleton getInstance(){
            if(singleton  == null){
                singleton = new Singleton();
            }
            return singleton;
        }
    }
    
  2. using a static final field

    private static final Singleton singleton = new Singleton();
    
    public static Singleton getSingleton() {
        return singleton;
    }
    

Whats the difference? (singlethreaded or multithreaded)

Updates: I am aware of Bill Pugh or enum method. I am not looking for the correct way, but I have only used 1. Is there really any difference b/w 1 or 2?

Answer

assylias picture assylias · Dec 5, 2012

The main difference is that with the first option , the singleton will only be initialised when getInstance is called, whereas with the second option, it will get initialized as soon as the containing class is loaded.

A third (preferred) option which is lazy and thread safe is to use an enum:

public enum Singleton {
    INSTANCE;
}