关于volatile和UNSAFE.getLong的取舍和区别?
最近在看JCTools的源码,在查看SPSC队列的时候,有个疑问,
既然producerIndex属性已经被volatile修饰了,为什么还有一个UNSAFE.getLong方法来获取,性能更高吗,为什么要这样取舍?
回答:
因为你这是 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
*/
以上是 关于volatile和UNSAFE.getLong的取舍和区别? 的全部内容, 来源链接: utcz.com/p/945177.html