Singleton In Java

Singleton in java is a class which has only one instance in whole application and provides a getInstance() method to access the singleton instance. There are many classes in JDK which is implemented using Singleton pattern like java.lang.Runtime which provides getRuntime() method to get access of it.

There are many ways to create singleton in java. These are : –

Singleton With Lazy Loading

Here instance of singleton class is created when we call getInstance(). That is why it is Lazy loading.

Singleton With Lazy Loading And Thread Safe

Source – www.javarevisited.blogspot.in

If we do not make instance variable volatile then Thread which is creating instance of Singleton is not able to communicate other thread, that instance has been created until it comes out of the Singleton block, so if Thread A is creating Singleton instance and just after creation lost the CPU, all other thread will not be able to see value of instance as not null and they will believe its still null.

Why because reader threads are not doing any locking and until writer thread comes out of synchronized block, memory will not be synchronized and value of instance will not be updated in main memory. With Volatile keyword in Java this is handled by Java himself and such updates will be visible by all reader threads.

Singleton With Early Loading

Since Singleton instance is static and final variable it initialized when class is first loaded into memory so creation of instance is inherently thread-safe.

Things To Consider
  • Constructor must be private.
  • Instance variable must be static and volatile(for thread safe).
  • Method must be static which is returning object.
  • Prakash

    Great interview example covering here lol!!