A data race and safe publication
Asked Answered
M

1

3
@State
@JCStressTest
public class M {
    class A {
        int f;
        A() {
            f = 42;
        }
    }
    private A a;

    @Actor
    void actor1(){
        a = new A();
    }
    @Actor
    void actor2(IntResult1 r){
        r.r1 = 1;
        if(a != null){
            r.r1 = a.f;
        }
    }
}

I tested it with a jcstress and I cannot get the output 0. I know that is is not obvious that I should see that output, but it's possible and I would like to see it. Is there any JVM option (like XX:....) to enforce it?

Mcilwain answered 2/9, 2017 at 22:36 Comment(0)
S
3

I know that is is not obvious that I should see that output, but it's possible and I would like to see it.

You are correct that your code does have a data race.

(There is no happens-before chain between f = 42 and ... = a.f deducible under the rules set out in the JMM. Therefore, it is not guaranteed that a.f will always see the value 42.)

However, the nature of this race is such that it will only occur in extremely rare scenarios. It would most likely require a system with multiple cores, and either high memory load or an involuntary thread context switch at just the wrong instant. And it would be dependent on the native code emitted by the JIT compiler1.

Is there any JVM option (like XX:....) to enforce it?

Unfortunately, no there isn't.


1 - Note you cannot draw sound inferences from the bytecodes. The JIT compiler is allowed (by the JLS / JVMS) to reorder instructions including memory reads and writes provided that they don't violate the JMM rules. This is important for performance of multi-threaded code.

Stacystadholder answered 3/9, 2017 at 1:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.