Java 8在sun.misc.Unsafe中增加了三个栅栏。

阅读他们的文档后,我感到困惑。

因此,我在网上搜索并找到了这个link

根据上面的页面,我相信这些方法在实践中几乎没有增加任何作用。如果我错了,请纠正我,大致来说,loadFence(),storeFence()和fullFence()分别对应于 volatile 读取,惰性写入和 volatile 写入,尽管从技术上讲,这些围栏要比 volatile 变量强。因此,loadFence()是获取隔离区,storeFence()是发布隔离区,fullFence()是完整隔离区。

但是,storeFence()的文档看起来很奇怪。

它说,

/**
 * Ensures lack of reordering of stores before the fence
 * with loads or stores after the fence.
 */
void storeFence();

那看起来不像是释放栅栏。应该如何使用?不应该这样吗
/**
 * Ensures lack of reordering of loads or stores before the fence
 * with stores after the fence.
 */
void storeFence();

我假设之前的表示较早,而之后的表示较晚。

编辑

当我说这些“栅栏在实践中什么也没加”时,我并不是说“我们不会在常规开发中使用它们”。

我的意思是,即使在Unsafe中没有这些方法,我们也可以得到这些“围栏”。如果我是正确的,那么在实践中,读取一个虚拟的volatile具有loadFence()的作用,而写入一个虚拟的volatile具有fullFence()的影响,而unsafe.putOrderedXXX()(或AtomicInteger.lazySet())具有这个作用。 storeFence()的。

它们可能有细微的差别,但是在当前的实现中,它们是可交换的。 (似乎由链接暗示)

这就是我的意思,“它们什么也没添加”。

另一个编辑

这个问题已经解决。

参见https://bugs.openjdk.java.net/browse/JDK-8038978

谢谢@ john-vint

最佳答案

实际上,JDK9中对此有所区别。有类似的问题被询问和澄清:

http://hg.openjdk.java.net/jdk9/jdk9/jdk/rev/84e19392365e

      /**
!      * Ensures that loads before the fence will not be reordered with loads and
!      * stores after the fence; a "LoadLoad plus LoadStore barrier".
!      *
!      * Corresponds to C11 atomic_thread_fence(memory_order_acquire)
!      * (an "acquire fence").
!      *
!      * A pure LoadLoad fence is not provided, since the addition of LoadStore
!      * is almost always desired, and most current hardware instructions that
!      * provide a LoadLoad barrier also provide a LoadStore barrier for free.
       * @since 1.8
       */
      public native void loadFence();

      /**
!      * Ensures that loads and stores before the fence will not be reordered with
!      * stores after the fence; a "StoreStore plus LoadStore barrier".
!      *
!      * Corresponds to C11 atomic_thread_fence(memory_order_release)
!      * (a "release fence").
!      *
!      * A pure StoreStore fence is not provided, since the addition of LoadStore
!      * is almost always desired, and most current hardware instructions that
!      * provide a StoreStore barrier also provide a LoadStore barrier for free.
       * @since 1.8
       */
      public native void storeFence();

      /**
!      * Ensures that loads and stores before the fence will not be reordered
!      * with loads and stores after the fence.  Implies the effects of both
!      * loadFence() and storeFence(), and in addition, the effect of a StoreLoad
!      * barrier.
!      *
!      * Corresponds to C11 atomic_thread_fence(memory_order_seq_cst).
       * @since 1.8
       */
      public native void fullFence();

关于Java Unsafe.storeFence()文档错误?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30600621/

10-10 03:53