什么时候在 Java 中使用 volatile boolean 而不是 AtomicBoolean 更可取? [英] When is it preferable to use volatile boolean in Java rather than AtomicBoolean?
问题描述
我查看了 SO 中的其他 volatile 与 Atomicxxxx 问题(包括这个) 并已阅读 java.util.current.atomic 的描述,我对其中的细微差别不太满意.
I've looked at the other volatile vs. Atomicxxxx questions in SO (including this one) and have read the description of java.util.current.atomic, and I am not quite satisfied with the nuances.
如果我试图在使用 volatile boolean
和 AtomicBoolean
之间做出决定,除了 AtomicBoolean 提供的原子读-修改-写操作之外,还有实际区别吗?(例如 compareAndSet()
和 getAndSet()
)
If I'm trying to decide between using volatile boolean
and AtomicBoolean
, are there practical differences besides the atomic read-modify-write operations offered by AtomicBoolean? (e.g. compareAndSet()
and getAndSet()
)
假设我有
volatile boolean flag;
然后一个或多个线程设置标志(但不清除它).如果我有一个线程读取标志,如果设置,则执行一个操作,然后清除标志,volatile
是否足够?
Then one or more threads set the flag (but not clear it). If I have one thread that reads the flag, and if set, does an action, and then clears the flag, is volatile
adequate?
AtomicBoolean 的成本是否比 volatile boolean 更高,就
Is there a higher cost to AtomicBoolean than volatile boolean, in terms of
- 内存空间
- 性能下降(
volatile boolean
似乎需要内存防护,AtomicBoolean
似乎需要内存防护 + 根据 java.util.current 对 CAS 操作进行一些小锁定.原子描述)
- memory space
- performance hit (
volatile boolean
appears to require memory fencing,AtomicBoolean
appears to require memory fencing + some minor locking on CAS operations as per the java.util.current.atomic description)
我的直觉是只使用 AtomicBoolean 并保持安全,但我想了解是否有使用 volatile boolean
代替的情况(例如,如果我有数千个实例和性能是一个问题).
My gut call is to just go with AtomicBoolean and be safe, but I want to understand if there's ever a situation to use volatile boolean
instead (e.g. if I had thousands of instances of them and performance were an issue).
推荐答案
基本上所有 AtomicBoolean
都是对象中的 volatile boolean
.
Essentially all AtomicBoolean
is a volatile boolean
in an object.
每个对象会有少量开销.可能微不足道,但可能有更多内存可以进入缓存.
There will be a small overhead per object. Probably insignificant, but possibly more memory to get into cache.
如果你需要使用AtomicBooleanFieldUpdater
,那么性能开销会很大.如果你不经常使用也没关系(如attach
在蔚来).
If you need to use AtomicBooleanFieldUpdater
then there is quite a lot of performance overhead.It can be okay if you aren't going to do it often (as attach
in NIO).
这篇关于什么时候在 Java 中使用 volatile boolean 而不是 AtomicBoolean 更可取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!