java: using volatile at one variable VS each variable

倾然丶 夕夏残阳落幕 提交于 2020-01-05 04:57:18

问题


the following problem:

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;

Is that better having only one volatile variable, or should i make each variable i could write/read on valatile?

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?

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?


回答1:


The example is so trivial so you might not see much of a difference performance-wise.

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.

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.



来源:https://stackoverflow.com/questions/57420559/java-using-volatile-at-one-variable-vs-each-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!