问题描述
以下问题:
volatile Object A;
volatile Object B;
volatile Object C;
Thread1:
reads and writes to A-C
Thread2:
the same as Thread1
所以我的问题是:如果我做这样的事情会更好:
So my question is: would it better if i do something like this:
Object A;
Object B;
Object C;
volatile boolean memoryBarrier=true;
Thread1:
Before read of A-C: read memoryBarrier
After some write of A-C: write memoryBarrier=true;
Thread2:
the same as Thread1:
Before read of A-C: read memoryBarrier
After some write of A-C: write memoryBarrier=true;
最好只具有一个volatile变量,还是应该让每个变量都能在易失性上进行读写?
Is that better having only one volatile variable, or should i make each variable i could write/read on valatile?
如果我每次都对我的secound解决方案中的memoryBarrier写入true,那可以触发写-读-发生在java中的关系语义之前吗?我想它没有被淘汰吗?
And is that ok, if i write each time true to my memoryBarrier in my secound solution?, to trigger the write-read- happens before relationsship semantic in java? I guess its not optimezed away?
因此,摘要:我的解决方案1和2在语义上是否相等?解决方案2更好吗?我是否可以始终将相同的值写入volatile变量,以在发生关系之前读取/写入volatile发生?
So the summary:Are my solution 1 and 2 semantically the equal?Is solution 2 better?Can i always write the same value a volatile variable to get read/write volatile happensbefore-relationsship?
推荐答案
该示例非常简单,因此您可能不会在性能方面看到太多差异.
The example is so trivial so you might not see much of a difference performance-wise.
我的直觉告诉我,先进行3次非易失性存储器访问后再进行一次volatile
访问,可能比连续进行3次volatile
访问更好.
My intuition tells me that having 3 non-volatile memory accesses followed by a single volatile
access is probably better than issuing 3 volatile
accesses in a row.
这三个volatile
内存访问是完全有序的(A发生-B发生-C发生),并且限制了编译器和处理器执行某些优化.非易失性版本不会在A,B和C之间建立任何先发生的关系,因此为编译器和处理器提供了更多利用内存级并行性/指令级并行性的自由.
Those three volatile
memory accesses are totally ordered (A happens-before B happens-before C) and restricts the compiler and processor from performing some optimizations. The non-volatile version establishes no happens-before relation between A, B, and C, and therefore give the compiler and processor more freedom to exploit memory-level parallelism/instruction-level parallelism.
这篇关于Java:在一个变量VS每个变量处使用volatile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!