My question is addressed to the mail:
https://shipilev.net/blog/2014/safe-public-construction/
public class UnsafeDCLFactory {
private Singleton instance;
public Singleton get() {
if (instance == null) {
synchronized (this) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
And, it is written:
Please note that we do several readings of the instance in this code, and at least “read 1” and “read 3” are read without any synchronization - that is, these readings are vivid. One of the Java memory models is the reordering capability for regular reads, otherwise the performance overhead would be prohibitive. Specificity, as indicated in the rules, the reading action can observe an unordered record through the race. It decided for each action to read, regardless of what other actions have already read the same place. In our example, this means that even though “read 1” can read a non-empty instance, the code then moves to return it, then it does another read, and it can read null, which will be returned!
. , , , . , , .
read 1 . read 3 null. , read 3 instance read 1 ( , Java Memory Model).
, , read 3 read 1 - - instance = new Singleton();
, , , read 3 store, ( ). read 1, store. .
, : read 1 -> store -> read 3
?
P.S. - ? , - ?
@Aleksey Shipilev.
- .
, .
Java Memory Model .
. , . ( - - , ). , read 3 read 1. , , . , Java -, read 3 read 1. , read3 null - , , , read 1 -null read 3 null, read 3 read 1 - .
( ())