Search code examples
javamultithreadingconcurrencyvolatile

java: using volatile at one variable VS each variable


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?


Solution

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