1. 以下就是java世界老幼皆知的double check方法
The problem here is not with sequential consistency. Code is being moved, not reordered. Many JVMs do not implement
4. 最後的解決辦法:D
Accept the synchronization of a
Forgo synchronization and use a
在文章中Peter Haggar不遺餘力的指出double check原理是多麼的不可靠。
原因: 類似SomeClass instance = new SomeClass();
之類的操作不是原子性的,用pseudo code 來表示就是:
mem = allocate(); //Allocate memory for Singleton object.
instance = mem; //Note that instance is now non-null, but
//has not been initialized.
ctorSingleton(instance); //Invoke constructor for Singleton passing instance
2. 然後Peter Haggar給出了個"解決辦法",俺被誤導了
這個方法似乎是可行的,但是有缺點:
1. 顯然,看起來太蠢笨了
2. 由於JIT Compiler的優化,這個也不會起作用
If this optimization takes place, you have the same out-of-order write problem we discussed earlier.
3. Another idea is to use the keyword volatile
for the variables inst
and instance
.
volatile
correctly regarding sequential consistency anyway. 4. 最後的解決辦法:D
getInstance()
method as shown in Listing 2.static
field.