How do you write a Thread Safe Singleton?
Submitted by: AdministratorThe 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;
}
}
Submitted by: Administrator
► 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;
}
}
Submitted by: Administrator
Read Online Java Patterns Job Interview Questions And Answers
Top Java Patterns Questions
☺ | Explain about semaphores? |
☺ | How do you write a Thread Safe Singleton? |
☺ | Explain about fully synchronized objects? |
☺ | Explain about locks? |
☺ | Explain the difference between Canonical and GoF form? |
Top Java Programming Language Categories
☺ | Core Java Interview Questions. |
☺ | Hibernate Interview Questions. |
☺ | Advanced Java Interview Questions. |
☺ | IBM WebSphere Interview Questions. |
☺ | Spring Framework Interview Questions. |