Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

singleton and public static variable Java

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?

like image 956
Achow Avatar asked Dec 05 '12 13:12

Achow


1 Answers

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;
}
like image 194
assylias Avatar answered Sep 17 '22 23:09

assylias