什么时候最好在Java中使用volatile boolean而不是AtomicBoolean? [英] When is it preferable to use volatile boolean in Java rather than AtomicBoolean?
问题描述
我查看了SO中的其他volatile和Atomicxxxx问题(包括 this one ),并已阅读说明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
似乎需要内存防护+
- 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)
我的gut调用只是使用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
是 / code>。
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
在NIO中)。
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屋!