Answers

Question and Answer:

  Home  Java Patterns

⟩ How do you write a Thread Safe Singleton?

The following are the steps to write a thread-safe singleton:

► Declare a Boolean variable, ‘instantiated’, to know the status of instantiation of a class, an object of Object class and a variable of the same class with initial value as null.

► Write a private constructor of this class

► Override getInstance() method. Check the Boolean state of the instance variable ‘instantiated’. If it is false, write a ‘synchronized’ block and test for the current class instance variable. If it is null create an object of the current class and assign it to the instance variable.

The following code illustrates this :

public class SampleSingleton {

private static boolean initialized = false;

private static Object obj = new Object();

private static SampleSingleton instance = null;

private SampleSingleton() {

// construct the singleton instance

}

public static SampleSingleton getInstance() {

if (!initialized) {

synchronized(obj) {

if (instance == null) {

instance = new SampleSingleton();

initialized = true;

}

}

}

return instance;

}

}

 160 views

More Questions for you: