且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

何时使用AtomicReference(Java)?是真的有必要吗?

更新时间:2023-10-26 19:12:04

这是一个参考文档非常清楚,它是一个身份比较,甚至使用 == 操作/docs/api/java/util/concurrent/atomic/AtomicReference.html#compareAndSet%28V,%20V%29rel =nofollow noreferrer>其说明

It's a reference, so that's what is compared. The documentation makes it very clear that it's an identity comparison, even using the == operation in its description.

我经常使用 AtomicReference 和其他原子类。分析表明,它们的性能比使用同步的等效方法更好。例如,对 AtomicReference get()操作只需要从主存储器提取,而类似的操作使用 synchronized 必须首先将线程缓存的任何值刷新到主存储器,然后执行其提取操作。

I use AtomicReference and other atomic classes very frequently. Profiling shows that they perform better than the equivalent methods using synchronization. For example, a get() operation on an AtomicReference requires only a fetch from main memory, while an a similar operation using synchronized must first flush any values cached by threads to main memory and then perform its fetch.

c $ c> AtomicXXX 类提供对比较和交换(CAS)操作的本机支持的访问。如果底层系统支持它,CAS将比在纯Java中使用 synchronized 块的任何方案更快。

The AtomicXXX classes provide access to native support for compare-and-swap (CAS) operations. If the underlying system supports it, CAS will be faster than any scheme cooked up with synchronized blocks in pure Java.