Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break double checked locking without volatile

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.

like image 364
HPCS Avatar asked Jan 12 '15 15:01

HPCS


1 Answers

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

like image 59
Aleksey Shipilev Avatar answered Sep 28 '22 03:09

Aleksey Shipilev