Java中的多线程状态可见性:有没有办法将JVM变成最坏的情况? [英] Multi-thread state visibility in Java: is there a way to turn the JVM into the worst case scenario?

查看:184
本文介绍了Java中的多线程状态可见性:有没有办法将JVM变成最坏的情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们的代码有2个线程(A和B)在某个地方引用了这个类的同一个实例:

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;

    // ... getter and setter

}

当线程A执行 myValueHolder.setValue(7)时,无法保证线程B将读取该值: myValueHolder.getValue ()可以 - 理论上 - 永远返回 1

When Thread A does myValueHolder.setValue(7), there is no guarantee that Thread B will ever read that value: myValueHolder.getValue() could - in theory - keep returning 1 forever.

然而在实践中,硬件迟早会清除二级缓存,因此线程B迟早会读取 7 (通常更早)。

In practice however, the hardware will clear the second level cache sooner or later, so Thread B will read 7 sooner or later (usually sooner).

有没有什么方法可以让JVM模拟最坏的情况,它会一直为线程B返回 1 那个在这些情况下用我们现有的测试测试我们的多线程代码会非常有用。

Is there any way to make the JVM emulate that worst case scenario for which it keeps returning 1 forever for Thread B? That would be very useful to test our multi-threaded code with our existing tests under those circumstances.

推荐答案

jcstress 维护者在这里。有多种方法可以回答这个问题。

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


  1. 最简单的解决方案是将getter包装在循环中,然后让JIT提升它。这可以用于非易失性字段读取,并通过编译器优化模拟可见性失败。

  2. 更复杂的技巧涉及获取OpenJDK的调试版本,并使用 - XX:+ StressLCM -XX:+ StressGCM ,有效地进行指令调度模糊测试。有问题的负载可以浮动到您可以通过产品的常规测试检测到的地方。

  3. 我不确定是否存在实际硬件保持写入值足够长的不透明缓存一致性,但使用jcstress构建测试用例有点容易。你必须记住,(1)中的优化也可能发生,所以我们需要采用一种技巧来防止这种情况。我认为就像这样应该有效。

  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.

这篇关于Java中的多线程状态可见性:有没有办法将JVM变成最坏的情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆