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

后端 未结 7 1572
轻奢々
轻奢々 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条回答
  •  故里飘歌
    2021-02-04 09:22

    Not on a real machine, sadly testing multi-threaded code will remain difficult.

    As you say, the hardware will clear the second level cache and the JVM has no control over that. The JSL only specifies what must happen and this is a case where B might never see the updated value of value.

    The only way to force this to happen on a real machine is to alter the code in such a way to void your testing strategy i.e. you end up testing different code.

    However, you might be able to run this on a simulator that simulates hardware that doesn't clear the second level cache. Sounds like a lot of effort though!

提交回复
热议问题