The wikipedia article on Singletons mentions a few thread safe ways to implement the structure in Java. For my questions, let's consider Singletons that have lengthy initialization procedures and are acccessed by many threads at once.
Firstly, is this unmentioned method thread-safe, and if so, what does it synchronize on?
public class Singleton {
private Singleton instance;
private Singleton() {
//lots of initialization code
}
public static synchronized Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
Secondly, why is the following implementation thread safe AND lazy in initialization? What exactly happens if two threads enter the getInstance()
method at the same time?
public class Singleton {
private Singleton() {
//lots of initialization code
}
private static class SingletonHolder {
public static final Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}
Finally, in the second example, what if one thread gets an instance first and another thread gets an instance and tries to perform actions on it before the constructor has finished in the first thread? Can you get into an unsafe state then?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…