[英]Java equivalent to Thread.MemoryBarrier
In Java, how can I explicitly trigger a full memory fence/barrier, equal to the invocation of 在Java中,我如何显式触发完整的内存fence / barrier,等于调用
System.Threading.Thread.MemoryBarrier();
in C#? 在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
. 我知道,因为Java 5读取和写入volatile
变量已经导致了完整的内存限制,但是可能存在一种没有volatile
的(有效)方式。
Compared to MemoryBarrier()
, Java's happens-before is a much sharper tool, leaving more leeway for aggressive optimization while maintaining thread safety. 与MemoryBarrier()
相比,Java 发生在以前是一个更加锐利的工具,在保持线程安全的同时为积极优化留下了更多的余地。
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. 正如您所料,更清晰的工具也需要更加谨慎地使用,这就是如何描述volatile
变量访问的语义。 You must write to a volatile
variable on the write site and read from the same volatile on each reading site. 您必须写入写入站点上的volatile
变量,并从每个读取站点上的相同volatile中读取。 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. 通过暗示,您可以拥有任意数量的独立的,本地化的“内存障碍”,每个volatile
变量一个,并且每个仅保护从该变量可到达的状态。
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. 完整的习语通常被称为“安全发布”(尽管这是一个更通用的术语),并且意味着填充将在线程之间共享的不可变对象图,然后将对它的引用写入volatile
变量。
There are no direct equivalent. 没有直接的等价物。 Use volatile field or more high level things. 使用volatile字段或更高级别的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.