Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Singleton behave when two threads call the "getInstance()" at the same time?

How does Singleton behave when two threads call the "getInstance()" at the same time? What are the best practices to protect it?

like image 834
xpollcon Avatar asked Jan 05 '14 23:01

xpollcon


1 Answers

This is only an issue at all if you use lazy initialization on the singleton. If you use eager initialization then the JVM guarantees to sort it all out for you.

For lazy initialization you need to either synchronize (although you can make it volatile and use double-check locking to avoid synchronized blocks all the time) or embed it within an inner class where it is not lazy initialized.

peter.petrov's answer now covers most of the options well, there is one final approach to thread safe lazy initialization though that is not covered and it is probably the neatest one.

public class Singleton {

  // Prevent anyone else creating me as I'm a singleton
  private Singleton() {
  }

  // Hold the reference to the singleton instance inside a static inner class
  private static class SingletonHolder {
    static Singleton instance = new Singleton();    
  }

  // Return the reference from inside the inner class
  public static Singleton getInstance() {
    return SingletonHolder.instance;
  }

}

Java does lazy loading on classes, they are only loaded when first accessed. This applies to inner classes too...

like image 139
Tim B Avatar answered Sep 28 '22 08:09

Tim B