I like the simplicity of the "eager singleton" in java, and most articles about it call its creation thread safe.
class Singleton {
public static final Singleton instance = new Singleton ();
private Singleton (){};
public static Singleton getInstance(){
return instance;
}
}
However I have heard some claims that its creation might not be thread safe after all. For example one source claimed that it is not safe if more than 1 class loader or App domain is used.
Is the creation of the "Eager Singleton" guaranteed by the JVM to be thread safe, so that, for example, 2 threads don't accidentally create the singleton at the same time?
Edit:
Is the keyword final required for thread safet of the object creation? Is it not thread safe if the field is not final?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…