简体   繁体   English

发生之前的关系中的微妙时刻

[英]Subtle moments in Happens-Before relationship

This question concerns JMM: https://www.cs.umd.edu/~pugh/java/memoryModel/jsr133.pdf 这个问题与JMM有关: https : //www.cs.umd.edu/~pugh/java/memoryModel/jsr133.pdf

Could you please explain the following expression from JMM Specification (this is the section 5 on page 13): 您能否解释一下JMM规范中的以下表达式(这是第13页的第5节):

More specifically, if two actions share a happens-before relationship, they do not necessarily have to appear to have happened in that order to any code with which they do not share a happens- before relationship. 更具体地说,如果两个动作共享事前发生关系,则对于未与之发生事前关系的任何代码,它们不一定必须按照该顺序发生。 Writes in one thread that are in a data race with reads in another thread may, for example, appear to occur out of order to those reads. 例如,在一个数据竞争中的一个线程中进行写操作而在另一个线程中进行读操作可能看起来与这些读操作的发生顺序不一致。

If possible please provide Execution Traces that reflect this issue. 如果可能,请提供反映此问题的执行跟踪。

The paragraph preceding the paragraph you quote has stated, that the fact that an action a is in a happens-before relationship with an action b, does not mean that a is really executed before b. 您引用的段落前面的段落已声明,动作a与动作b处于发生前关系这一事实,并不意味着a确实在b之前执行。 For example, in the code snippet 例如,在代码片段中

x = 10;
y = 20;

the two write action are in a happens-before relationship because they occur in the same thread. 这两个写操作处于事前发生的关系,因为它们发生在同一线程中。 However, they may actually be swapped (by the compiler, by the JVM or even by the processor) because this swapping cannot be observed from within the thread itself. 但是,实际上可能会交换它们(由编译器,JVM甚至由处理器),因为无法从线程本身内部观察到这种交换。

However, it can be observed by another thread (and this is specifically allowed by the Java memory model). 但是,它可以被另一个线程观察到(Java内存模型明确允许这样做)。 So another thread which reads those two variables, without some form of synchronization, may observe that y is changed to 20 before x is changed to 10. (The absense of synchronization makes sure that the write are in a data race with the reads in the other thread.) 因此,另一个读取这两个变量而没有某种形式的同步的线程可能会观察到,在x更改为10之前,y更改为20。(缺少同步确保了写操作与读操作中的数据处于竞争状态。其他线程。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM