Java Design Patterns Question:
Download Job Interview Questions and Answers PDF
How do you write a Thread Safe Singleton?
Answer:
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;
}
}
► 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;
}
}
Download Java Patterns Interview Questions And Answers
PDF
Previous Question | Next Question |
What is an analysis pattern? | What is Singleton pattern? |