本文介绍了为什么CAS(原子)操作比同步或易失性操作快的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,synced关键字将本地线程缓存与主内存同步. volatile关键字基本上总是在每次访问时从主存储器读取变量.当然,访问主内存比本地线程缓存要昂贵得多,因此这些操作很昂贵.但是,CAS操作使用低级硬件操作,但仍必须访问主内存.那么CAS操作又如何更快?

解决方案

我相信关键因素就在您所说的-CAS机制使用低级硬件指令,这些指令可实现最小的缓存刷新和争用解决.

其他两种机制(synchronizationvolatile)使用不同的体系结构技巧,这些技巧在所有不同的体系结构中更常见.

CAS指令在大多数现代体系结构中都可以以一种或另一种形式使用,但是每种体系结构中都有不同的实现方式.

来自 Brian Goetz (据说)的有趣报价

From what I understand, synchronized keyword syncs local thread cache with main memory. volatile keyword basically always reads the variable from the main memory at every access. Of course accessing main memory is much more expensive than local thread cache so these operations are expensive. However, a CAS operation use low level hardware operations but still has to access main memory. So how is a CAS operation any faster?

解决方案

I believe the critical factor is as you state - the CAS mechanisms use low-level hardware instructions that allow for the minimal cache flushing and contention resolution.

The other two mechanisms (synchronization and volatile) use different architectural tricks that are more generally available across all different architectures.

CAS instructions are available in one form or another in most modern architectures but there will be a different implementation in each architecture.

Interesting quote from Brian Goetz (supposedly)

这篇关于为什么CAS(原子)操作比同步或易失性操作快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 07:55