数据竞赛和安全发布 [英] A data race and safe publication

查看:68
本文介绍了数据竞赛和安全发布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@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;
        }
    }
}

我用jcstress测试了它,但无法获得输出0.我知道应该看到该输出并不明显,但是有可能,并且我希望看到它.是否有任何JVM选项(例如XX:....)来实施?

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?

推荐答案

我知道我应该看到该输出并不明显,但是有可能并且我想看到它.

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.

(根据JMM中规定的规则,在f = 42... = a.f之间没有可推论的先发生链.因此,不能保证 a.f将始终看到值42.)

(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.)

但是,这场比赛的性质使得它只会在极为罕见的情况下发生.最有可能需要一个具有多个内核的系统,并且在错误的时刻立即执行高内存负载或非自愿线程上下文切换.并且这将取决于JIT编译器 1 发出的本机代码.

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.

是否有任何JVM选项(例如XX:....)来实施?

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

不幸的是,没有.

1-注意您不能从字节码中得出声音推断. (由JLS/JVMS允许 允许JIT编译器重新排序包括内存读写的指令,前提是它们不违反JMM规则.这对于多线程代码的性能很重要.

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.

这篇关于数据竞赛和安全发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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