我什么时候需要在 Java 中使用 AtomicBoolean?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4501223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When do I need to use AtomicBoolean in Java?
提问by yart
How I can use AtomicBoolean and what is that class for?
我如何使用 AtomicBoolean 以及该类的用途是什么?
采纳答案by Bozho
When multiple threads need to check and change the boolean. For example:
当多个线程需要检查和更改布尔值时。例如:
if (!initialized) {
initialize();
initialized = true;
}
This is not thread-safe. You can fix it by using AtomicBoolean
:
这不是线程安全的。您可以使用AtomicBoolean
以下方法修复它:
if (atomicInitialized.compareAndSet(false, true)) {
initialize();
}
回答by Aravind Yarram
Here is the notes (from Brian Goetz book) I made, that might be of help to you
这是我做的笔记(来自Brian Goetz 的书),可能对你有帮助
AtomicXXX classes
AtomicXXX 类
provide Non-blocking Compare-And-Swap implementation
Takes advantage of the support provide by hardware (the CMPXCHG instruction on Intel) When lots of threads are running through your code that uses these atomic concurrency API, they will scale much better than code which uses Object level monitors/synchronization. Since, Java's synchronization mechanisms makes code wait, when there are lots of threads running through your critical sections, a substantial amount of CPU time is spent in managing the synchronization mechanism itself (waiting, notifying, etc). Since the new API uses hardware level constructs (atomic variables) and wait and lock free algorithms to implement thread-safety, a lot more of CPU time is spent "doing stuff" rather than in managing synchronization.
not only offer better throughput, but they also provide greater resistance to liveness problems such as deadlock and priority inversion.
提供非阻塞比较和交换实现
利用硬件提供的支持(Intel 上的 CMPXCHG 指令)当大量线程通过使用这些原子并发 API 的代码运行时,它们将比使用对象级监视器/同步的代码更好地扩展。由于 Java 的同步机制使代码等待,当有大量线程通过临界区运行时,大量 CPU 时间用于管理同步机制本身(等待、通知等)。由于新 API 使用硬件级构造(原子变量)以及等待和无锁算法来实现线程安全,因此更多的 CPU 时间用于“做事”而不是管理同步。
不仅提供了更好的吞吐量,而且它们还提供了对活性问题(例如死锁和优先级反转)的更大抵抗力。
回答by Cameron Skinner
The AtomicBoolean
class gives you a boolean value that you can update atomically. Use it when you have multiple threads accessing a boolean variable.
该AtomicBoolean
班为您提供了一个布尔值,你可以原子更新。当您有多个线程访问布尔变量时使用它。
The java.util.concurrent.atomic package overviewgives you a good high-level description of what the classes in this package do and when to use them. I'd also recommend the book Java Concurrency in Practiceby Brian Goetz.
在java.util.concurrent.atomic包概述给你的东西在这个包中的类做和何时使用它们好高层次的描述。我还推荐Brian Goetz所著的Java Concurrency in Practice一书。
回答by John Vint
There are two main reasons why you can use an atomic boolean. First its mutable, you can pass it in as a reference and change the value that is a associated to the boolean itself, for example.
可以使用原子布尔值有两个主要原因。首先它是可变的,例如,您可以将它作为引用传入并更改与布尔值本身相关联的值。
public final class MyThreadSafeClass{
private AtomicBoolean myBoolean = new AtomicBoolean(false);
private SomeThreadSafeObject someObject = new SomeThreadSafeObject();
public boolean doSomething(){
someObject.doSomeWork(myBoolean);
return myBoolean.get(); //will return true
}
}
and in the someObject class
在 someObject 类中
public final class SomeThreadSafeObject{
public void doSomeWork(AtomicBoolean b){
b.set(true);
}
}
More importantly though, its thread safe and can indicate to developers maintaining the class, that this variable is expected to be modified and read from multiple threads. If you do not use an AtomicBoolean you must synchronize the boolean variable you are using by declaring it volatile or synchronizing around the read and write of the field.
更重要的是,它的线程安全并且可以向维护类的开发人员表明,这个变量应该被修改并从多个线程读取。如果您不使用 AtomicBoolean,则必须通过将其声明为 volatile 或同步该字段的读取和写入来同步您正在使用的布尔变量。
回答by OscarRyz
Excerpt from the package description
包装说明摘录
Package java.util.concurrent.atomic description: A small toolkit of classes that support lock-free thread-safe programming on single variables.[...]
The specifications of these methods enable implementations to employ efficient machine-level atomic instructions that are available on contemporary processors.[...]
Instances of classes AtomicBoolean, AtomicInteger, AtomicLong, and AtomicReference each provide access and updates to a single variable of the corresponding type.[...]
The memory effects for accesses and updates of atomics generally follow the rules for volatiles:
- get has the memory effects of reading a volatile variable.
- set has the memory effects of writing (assigning) a volatile variable.
- weakCompareAndSet atomically reads and conditionally writes a variable, is ordered with respect to other memory operations on that variable, but otherwise acts as an ordinary non-volatile memory operation.
- compareAndSet and all other read-and-update operations such as getAndIncrement have the memory effects of both reading and writing volatile variables.
包 java.util.concurrent.atomic 描述:一个支持单变量无锁线程安全编程的类的小工具包。[...]
这些方法的规范使实现能够采用当代处理器上可用的高效机器级原子指令。[...]
AtomicBoolean、AtomicInteger、AtomicLong 和 AtomicReference 类的实例均提供对相应类型的单个变量的访问和更新。[...]
原子的访问和更新的记忆效应一般遵循 volatile 的规则:
- get 具有读取易失性变量的记忆效应。
- set 具有写入(分配)易失性变量的记忆效应。
- weakCompareAndSet 原子地读取和有条件地写入变量,相对于对该变量的其他内存操作进行排序,但在其他方面充当普通的非易失性内存操作。
- compareAndSet 和所有其他读取和更新操作(例如 getAndIncrement)都具有读取和写入易失性变量的记忆效应。