据我了解,synchronized关键字将本地线程缓存与主内存同步。 volatile 关键字基本上总是在每次访问时从主内存中读取变量。当然,访问主内存比本地线程缓存要昂贵得多,因此这些操作的成本很高。然而,CAS 操作使用低级硬件操作,但仍然必须访问主存储器。那么 CAS 操作如何更快呢?
最佳答案
我认为关键因素正如您所说 - CAS 机制使用低级硬件指令,可以实现最少的缓存刷新和争用解决。
其他两种机制(同步
和 volatile
)使用不同的架构技巧,这些技巧在所有不同的架构中更普遍可用。
在大多数现代架构中,CAS 指令都以一种或另一种形式提供,但每种架构中都会有不同的实现。
来自 Brian Goetz 的有趣引用(据说)
The relative speed of the operations is largely a non-issue. What is relevant is the difference in scalability between lock-based and non-blocking algorithms. And if you're running on a 1 or 2 core system, stop thinking about such things.
Non-blocking algorithms generally scale better because they have shorter "critical sections" than lock-based algorithms.
关于atomic - 为什么 CAS(原子)操作比同步或 volatile 操作更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19623026/