There's only one problem with it -- it doesn't work. Why not? The most obvious reason is that the writes which initialize instanceand the write to the instance field can be reordered by the compiler or the cache, which would have the effect of returning what appears to be a partially constructed Something. The result would be that we read an uninitialized object. There are lots of other reasons why this is wrong, and why algorithmic corrections to it are wrong.but after java1.2, JMM has undergone a fundamental change, allocating space, initialization, and calling the construction method will only be completed in the working storage area of the thread.When there is no copy assignment to the main storage area, it is absolutely impossible for other threads to see this process. And the process of copying this field to the main memory area, there is no possibility that the space is not initialized or the construction method is not called after the space is allocated.
public class SingletonDemo {
private static SingletonDemo instance = null;
private SingletonDemo() {
}
public static SingletonDemo getSingletonDemo() {
if (instance == null) {
synchronized (SingletonDemo.class){
if (instance == null) {
instance = new SingletonDemo();
}
}
}
return instance;
}
Aucun commentaire:
Enregistrer un commentaire