One of the article mentions an issue with "Double Check Locking"
. Please see the below example
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 = ...
}
}
Reason:- (Please note the order of execution by the numbering)
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!
Question :
As the creation of the new instance(new MyBrokenFactory()) is done from the synchronized block, will the lock be released before the entire initialization is completed (private MyBrokenFactory() is completely executed) ?
Reference - https://www.javamex.com/tutorials/double_checked_locking.shtml
Please explain.