Java equivalent of Thread.MemoryBarrier
In Java, how can I explicitly call a full memory fence / barrier equal to the call
System.Threading.Thread.MemoryBarrier();
in C #?
I know that since Java 5 reads and writes to volatile
, variables cause a full fetch of memory, but maybe there is a (efficient) way without volatile
.
source to share
Compared to MemoryBarrier()
, Java comes earlier - it's a much sharper tool, leaving more room for aggressive optimization while maintaining thread safety.
A sharper tool, as you would expect, also requires more care to use correctly, and this is how the semantics of variable access can be described volatile
. You have to write a variable volatile
on the write site and read it from the same volatile on each read site. It is understood that you can have any number of independent localized "memory barriers", one per variable volatile
, and each protects only the state accessible from that variable.
The full idiom is usually called "publish safe" (although this is a more general term) and implies filling in an immutable object graph that will be shared between threads, and then writing a variable reference volatile
.
source to share