I have implemented the Singleton class as below:
public class Singleton {
private static Singleton instance = null;
private Singleton() {
}
private synchronized static void createInstance() {
instance = new Singletone();
}
public static Singleton getInstance() {
if(instance == null){
createInstance();
}
return instance;
}
}
But I want to know if it is a correct implementation of a singleton.
Are there any problem in multithreaded environment.
Your implementation is almost correct. The problem is that it is not thread-safe. 2 separate threads may enter
getInstance()simultaneously, check that instance is null and then create 2 instances of your class. Here is the fix:Please pay attention on word
synchronized.