136

Please clarify my queries regarding Singleton and Multithreading:

  • What is the best way to implement Singleton in Java, in a multithreaded environment?
  • What happens when multiple threads try to access getInstance() method at the same time?
  • Can we make singleton's getInstance() synchronized?
  • Is synchronization really needed, when using Singleton classes?
0

8 Answers 8

241

Yes, it is necessary. There are several methods you can use to achieve thread safety with lazy initialization:

Draconian synchronization:

private static YourObject instance;

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

This solution requires that every thread be synchronized when in reality only the first few need to be.

Double check synchronization:

private static final Object lock = new Object();
private static volatile YourObject instance;

public static YourObject getInstance() {
    YourObject r = instance;
    if (r == null) {
        synchronized (lock) {    // While we were waiting for the lock, another 
            r = instance;        // thread may have instantiated the object.
            if (r == null) {  
                r = new YourObject();
                instance = r;
            }
        }
    }
    return r;
}

This solution ensures that only the first few threads that try to acquire your singleton have to go through the process of acquiring the lock.

Initialization on Demand:

private static class InstanceHolder {
    private static final YourObject instance = new YourObject();
}

public static YourObject getInstance() {
    return InstanceHolder.instance;
}

This solution takes advantage of the Java memory model's guarantees about class initialization to ensure thread safety. Each class can only be loaded once, and it will only be loaded when it is needed. That means that the first time getInstance is called, InstanceHolder will be loaded and instance will be created, and since this is controlled by ClassLoaders, no additional synchronization is necessary.

39
  • 26
    Warning - be careful with double-checked synchronization. It doesn't work properly with pre-Java 5 JVMs due to "issues" with the memory model.
    – Stephen C
    Commented Jun 23, 2012 at 3:06
  • 3
    -1 Draconian synchronization and Double check synchronization getInstance()-method must be static!
    – Grim
    Commented Sep 29, 2013 at 9:58
  • 2
    @PeterRader They don't need to be static, but it might make more sense if they were. Amended as requested.
    – Jeffrey
    Commented Sep 29, 2013 at 17:26
  • 4
    You're implementation of double checked locking isn't guaranteed to work. It's actually explained in the article you cited for double checked locking. :) There is an example in there using volatile that works properly for 1.5 and higher (double checked locking is just plain broken below 1.5). The initialization on demand holder also cited in the article would probably be a simpler solution in your answer.
    – stuckj
    Commented May 8, 2015 at 16:05
  • 2
    @MediumOne AFAIK, r is not needed for correctness. It's just an optimization to avoid accessing the volatile field, since that's far more expensive than accessing a local variable.
    – Jeffrey
    Commented Jan 2, 2019 at 13:56
86

This pattern does a thread-safe lazy-initialization of the instance without explicit synchronization!

public class MySingleton {

     private static class Loader {
         static final MySingleton INSTANCE = new MySingleton();
     }

     private MySingleton () {}

     public static MySingleton getInstance() {
         return Loader.INSTANCE;
     }
}

It works because it uses the class loader to do all the synchronization for you for free: The class MySingleton.Loader is first accessed inside the getInstance() method, so the Loader class loads when getInstance() is called for the first time. Further, the class loader guarantees that all static initialization is complete before you get access to the class - that's what gives you thread-safety.

It's like magic.

It's actually very similar to the enum pattern of Jhurtado, but I find the enum pattern an abuse of the enum concept (although it does work)

14
  • 14
    Synchronization is still present, it's just enforced by the JVM instead of by the programmer.
    – Jeffrey
    Commented Jun 23, 2012 at 1:11
  • 2
    I understand it makes no difference to the JVM, I am just saying it made a difference to me as far as self-documented code goes. I've just never seen all caps in Java without the "final" keyword before (or enum), got a bit of cognitive dissonance. For someone programming Java full time, it probably would not make a difference, but if you jump languages back and forth, it helps to be explicit. Ditto for newbies. Although, I am sure one can adapt to this style pretty quick; all caps is probably enough. Don't mean to nit pick, I liked your post. Commented Oct 23, 2014 at 16:23
  • 1
    Excellent answer, though I didn't get some part of it. Can you elaborate "Further, the class loader guarantees that all static initialization is complete before you get access to the class - that's what gives you thread-safety." , how that helps in thread safety, I'm a little confused about that. Commented Dec 26, 2014 at 18:33
  • 2
    @wz366 actually, although it's not necessary, I agree for style reasons (since it is effectively final because no other code can access it) final should be added. Done.
    – Bohemian
    Commented Sep 27, 2017 at 18:11
  • 1
    How would I pass an argument to the MySingleton constructor inside the inner class if the getInstance method requires a parameter?
    – Robur_131
    Commented Aug 17, 2019 at 20:47
24

If you are working on a multithreaded environment in Java and need to gurantee all those threads are accessing a single instance of a class you can use an Enum. This will have the added advantage of helping you handle serialization.

public enum Singleton {
    SINGLE;
    public void myMethod(){  
    }
}

and then just have your threads use your instance like:

Singleton.SINGLE.myMethod();
0
10

Yes, you need to make getInstance() synchronized. If it's not there might arise a situation where multiple instances of the class can be made.

Consider the case where you have two threads that call getInstance() at the same time. Now imagine T1 executes just past the instance == null check, and then T2 runs. At this point in time the instance is not created or set, so T2 will pass the check and create the instance. Now imagine that execution switches back to T1. Now the singleton is created, but T1 has already done the check! It will proceed to make the object again! Making getInstance() synchronized prevents this problem.

There a few ways to make singletons thread-safe, but making getInstance() synchronized is probably the simplest.

2
  • Will it help by putting object creation code in Synchronized block, instead of making entire method synchronization?
    – RickDavis
    Commented Jun 23, 2012 at 0:54
  • @RaoG No. You want both the check and the creation in the synchronization block. You need those two operations happen together without interruptions or the situation I described above may happen.
    – Oleksi
    Commented Jun 23, 2012 at 0:56
8

Enum singleton

The simplest way to implement a Singleton that is thread-safe is using an Enum

public enum SingletonEnum {
  INSTANCE;
  public void doSomething(){
    System.out.println("This is a singleton");
  }
}

This code works since the introduction of Enum in Java 1.5

Double checked locking

If you want to code a “classic” singleton that works in a multithreaded environment (starting from Java 1.5) you should use this one.

public class Singleton {

  private static volatile Singleton instance = null;

  private Singleton() {
  }

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

This is not thread-safe before 1.5 because the implementation of the volatile keyword was different.

Early loading Singleton (works even before Java 1.5)

This implementation instantiates the singleton when the class is loaded and provides thread safety.

public class Singleton {

  private static final Singleton instance = new Singleton();

  private Singleton() {
  }

  public static Singleton getInstance() {
    return instance;
  }

  public void doSomething(){
    System.out.println("This is a singleton");
  }

}
0
2

You can also use static code block to instantiate the instance at class load and prevent the thread synchronization issues.

public class MySingleton {

  private static final MySingleton instance;

  static {
     instance = new MySingleton();
  }

  private MySingleton() {
  }

  public static MySingleton getInstance() {
    return instance;
  }

}
3
  • @Vimsha A couple other things. 1. You should make instance final 2. You should make getInstance() static.
    – John Vint
    Commented Jun 12, 2014 at 19:06
  • What would you do if you want to create a thread in the singleton. Commented Jan 29, 2015 at 8:58
  • @arun-george use a thread pool, a single thread pool if needed, and surround with a while(true)-try-catch-throwable if you want to ensure your thread never dies, no matter what error?
    – tgkprog
    Commented Feb 6, 2015 at 15:41
0

What is the best way to implement Singleton in Java, in a multithreaded environment?

Refer to this post for best way to implement Singleton.

What is an efficient way to implement a singleton pattern in Java?

What happens when multiple threads try to access getInstance() method at the same time?

It depends on the way you have implemented the method.If you use double locking without volatile variable, you may get partially constructed Singleton object.

Refer to this question for more details:

Why is volatile used in this example of double checked locking

Can we make singleton's getInstance() synchronized?

Is synchronization really needed, when using Singleton classes?

Not required if you implement the Singleton in below ways

  1. static intitalization
  2. enum
  3. LazyInitalaization with Initialization-on-demand_holder_idiom

Refer to this question fore more details

Java Singleton Design Pattern : Questions

0
public class Elvis { 
   public static final Elvis INSTANCE = new Elvis();
   private Elvis () {...}
 }

Source : Effective Java -> Item 2

It suggests to use it, if you are sure that class will always remain singleton.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.