8

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.

Raedwald
  • 46,613
  • 43
  • 151
  • 237
HPCS
  • 1,434
  • 13
  • 22
  • 3
    The problem is you are probably running against an x86 processor. From what I know they issue a StoreLoad barrier after the object construction so in that case you will not see a partially constructed object. If you can get a sparc or other system that handles construction different you would probably be able to see the problem. – John Vint Jan 12 '15 at 19:11

1 Answers1

2

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

Aleksey Shipilev
  • 18,599
  • 2
  • 67
  • 86
  • I wonder if it's possible to update the examples? At least I've tried to run `UnsafeDCL` on jdk-13 and it would not fail anymore.. – Eugene Jul 09 '20 at 19:05