简体   繁体   中英

Java equivalent to Thread.MemoryBarrier

In Java, how can I explicitly trigger a full memory fence/barrier, equal to the invocation of

System.Threading.Thread.MemoryBarrier();

in C#?

I know that since Java 5 reads and writes to volatile variables have been causing a full memory fence, but maybe there is an (efficient) way without volatile .

Compared to MemoryBarrier() , Java's happens-before is a much sharper tool, leaving more leeway for aggressive optimization while maintaining thread safety.

A sharper tool, as you would expect, also requires more care to use properly, and that is how the semantics of volatile variable access could be described. You must write to a volatile variable on the write site and read from the same volatile on each reading site. By implication you can have any number of independent, localized "memory barriers", one per a volatile variable, and each guards only the state reachable from that variable.

The full idiom is usually referred to as "safe publication" (although this is a more general term) and implies populating an immutable object graph which will be shared between threads, then writing a reference to it to a volatile variable.

Java 8, via JEP 108 added another possibility. Access to three fences have been to the Java API, fullFence, loadFence and storeFence.

There are no direct equivalent. Use volatile field or more high level things.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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