How to create thread-safe singleton objects in Java without using ‘synchronized’?

How to create thread-safe singleton objects in Java without using ‘synchronized’?

Ninja Asked on 18th September 2018 in Design Pattern.
Add Comment
1 Answer(s)
Best answer

Thread-safe singleton class can be created using inner static class approach.

public class Singleton {
 private Singleton() { }
 private static class SingletonHolder {
  private static final Singleton INSTANCE = new Singleton();
 }
 public static Singleton getInstance(){
  return SingletonHolder.INSTANCE;
 }
}

Here the private static inner class contains the instance of the Singleton class. When the Singleton class is loaded, SingletonHolder class is not loaded into memory. SingletonHolder class gets loaded on first invocation of the getInstance method and creates the Singleton class instance. Java Language Specification guarantees the class initialization process to be serial (non-concurrent) so no synchronization is required in the getInstance method. This solution guarantees single instance and achieves better performance than using synchronized keyword.

Ninja Answered on 18th September 2018.
Add Comment