Reputation: 1454
I know that double check locking without volatile
variable is not safe based on this link http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
class Foo {
private Helper helper = null;
public Helper getHelper() {
if (helper == null) {
synchronized(this) {
if (helper == null) {
helper = new Helper();
}
}
}
return helper;
}
}
I want to simulate this situation at my home computer. I have standard jdk1.7 and multicore processor. But I am not able to simulate the broken behaviour. I am using this test http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckTest.java that should simulate this. I also create some of my test, but without success. Do you have any idea how to simulate the situation when this double check idiom without volatile is broken? So it returns partially created Helper class.
Upvotes: 8
Views: 344
Reputation: 18847
On x86, it requires either a class with large amount of fields, so that initializing stores spill over publication, like this: http://cs.oswego.edu/pipermail/concurrency-interest/2015-January/013861.html
Or, you have to munge compiler to randomize instruction scheduler. On non-TSO architectures like ARM this can be demonstrated without any tricks, see: http://shipilev.net/blog/2014/safe-public-construction/#_correctness
Upvotes: 2