关于volatile和UNSAFE.getLong的取舍和区别?

新手上路,请多包涵

最近在看JCTools的源码,在查看SPSC队列的时候,有个疑问,
image.png
image.png
既然producerIndex属性已经被volatile修饰了,为什么还有一个UNSAFE.getLong方法来获取,性能更高吗,为什么要这样取舍?

阅读 1.8k
2 个回答

因为你这是 Spsc 呀。

反正只有一个线程,没必要读的时候也 volatile,能省一点儿 LoadLoad Memory Barrier 是一点儿。

直接读会快啊,然后另一方面看作者的注释,作者应该是为了避开JIT,虽然volatile不会被JIT优化,但是毕竟JIT这种基本黑盒的东西,谁知道下一个版本又会多出来什么骚操作,直接unsafe读取,反而更简单可靠一些。

/**
 * Why should we resort to using Unsafe?<br>
 * <ol>
 * <li>To construct class fields which allow volatile/ordered/plain access: This requirement is covered by
 * {@link AtomicReferenceFieldUpdater} and similar but their performance is arguably worse than the DIY approach
 * (depending on JVM version) while Unsafe intrinsification is a far lesser challenge for JIT compilers.
 * <li>To construct flavors of {@link AtomicReferenceArray}.
 * <li>Other use cases exist but are not present in this library yet.
 * </ol>
 *
 * @author nitsanw
 */
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题