<分区>
其中一篇文章提到了 “Double Check Locking”
的问题。请看下面的例子
public class MyBrokenFactory {
private static MyBrokenFactory instance;
private int field1, field2 ...
public static MyBrokenFactory getFactory() {
// This is incorrect: don't do it!
if (instance == null) {
synchronized (MyBrokenFactory.class) {
if (instance == null)
instance = new MyBrokenFactory();
}
}
return instance;
}
private MyBrokenFactory() {
field1 = ...
field2 = ...
}
}
原因:-(请注意编号的执行顺序)
Thread 1: 'gets in first' and starts creating instance. 1. Is instance null? Yes. 2. Synchronize on class. 3. Memory is allocated for instance. 4. Pointer to memory saved into instance. [[Thread 2]] 7. Values for field1 and field2 are written to memory allocated for object. ..................... Thread 2: gets in just as Thread 1 has written the object reference to memory, but before it has written all the fields. 5. Is instance null? No. 6. instance is non-null, but field1 and field2 haven't yet been set! This thread sees invalid values for field1 and field2!
问题:
由于新实例(new MyBrokenFactory())的创建是从synchronized block 中完成的,在整个初始化完成之前(private MyBrokenFactory()完全执行)是否会释放锁?
引用 - https://www.javamex.com/tutorials/double_checked_locking.shtml
请解释。