Multi-thread state visibility in Java: is there a way to turn the JVM into the worst case scenario?

后端 未结 7 1551
轻奢々
轻奢々 2021-02-04 08:36

Suppose our code has 2 threads (A and B) have a reference to the same instance of this class somewhere:

public class MyValueHolder {

    private int value = 1;
         


        
7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-04 09:25

    jcstress maintainer here. There are multiple ways to answer that question.

    1. The easiest solution would be wrapping the getter in the loop, and let JIT hoist it. This is allowed for non-volatile field reads, and simulates the visibility failure with compiler optimization.
    2. More sophisticated trick involves getting the debug build of OpenJDK, and using -XX:+StressLCM -XX:+StressGCM, effectively doing the instruction scheduling fuzzing. Chances are the load in question will float somewhere you can detect with the regular tests your product has.
    3. I am not sure if there is practical hardware holding the written value long enough opaque to cache coherency, but it is somewhat easy to build the testcase with jcstress. You have to keep in mind that the optimization in (1) can also happen, so we need to employ a trick to prevent that. I think something like this should work.

提交回复
热议问题