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

问题描述

@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?

推荐答案

您是正确的,您的代码确实存在数据争用.

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编译器发出的本机代码.

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 compiler.

不幸的是,没有.

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

08-22 17:21