且构网

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

关于volatile和Atomic类的一些疑问?

更新时间:2023-09-29 18:33:52


声明1: - 只能安全地使用volatile变量对于单个加载或存储操作,不能应用于长或双变量。这些限制使得volatile变量的使用不常见

Statement 1:- "volatile variables can be safely used only for single load or store operation and can't be applied to long or double variales. These restrictions make the use of volatile variables uncommon"

什么?我相信这完全是错误的。也许你的书已经过时了。

What?! I believe this is simply flat-out wrong. Maybe your book is out of date.


声明2: - 挥发性整数不能与++运算符一起使用,因为++运算符包含多个指令.AtomicInteger类有一个方法,允许它保持的整数以原子方式递增。

Statement 2:- "A Volatile integer can not be used with the ++ operator because ++ operator contains multiple instructions.The AtomicInteger class has a method that allows the integer it holds to be incremented atomically."

正是它所说的。 ++运算符实际上转换为像这样的机器代码(在类似Java的伪代码中):

Exactly what it says. The ++ operator actually translates to machine code like this (in Java-like pseudocode):

sync_CPU_caches();
int processorRegister = variable;
processorRegister = processorRegister + 1;
variable = processorRegister;
sync_CPU_caches();

这不是线程安全的,因为即使它有内存屏障,并以原子方式读取,原子地写,不保证你不会在中间获得一个线程切换,并且处理器寄存器是CPU核心的本地(将它们看作CPU核心内部的局部变量)。但是 AtomicInteger 是线程安全的 - 它可能是使用特殊的机器代码指令实现的,比如比较和交换。

This is not thread-safe, because even though it has a memory barrier, and reads atomically, and writes atomically, it is not guaranteed that you won't get a thread switch in the middle, and processor registers are local to a CPU core (think of them as like "local variables" inside the CPU core). But an AtomicInteger is thread-safe - it probably is implemented using special machine code instructions such as compare-and-swap.