关于volatile和Atomic类的一些疑问? [英] Some doubts about volatile and Atomic classes?

查看:574
本文介绍了关于volatile和Atomic类的一些疑问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将通过Java线程书。我发现了这个陈述

i am going thru Java threads book. I came across this statement

声明1: - 易变量只能安全地用于单个加载或存储操作,不能
应用于长变量或双变量。这些限制使得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"

我没有得到单个加载或存储操作的含义?为什么不能将
应用于长期或双期变量?

I did not get what does single load or store operation mean here? why volatile can't be applied to long or double variales?

语句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."

为什么Volatile整数不能与++运算符一起使用以及AtomicInteger如何解决它?

Why Volatile integer can not be used with the ++ operator and how AtomicInteger addresses it?

推荐答案


声明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.

这篇关于关于volatile和Atomic类的一些疑问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆