How I can use AtomicBoolean and what is that class for?
5 Answers
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:
if (atomicInitialized.compareAndSet(false, true)) {
initialize();
}
-
71It doesn't look like a real-world example - other thread can see
truewheninitialize()haven't been completed. So, it works only if other threads don't care about completion ofinitialize().– axtavtDec 21, 2010 at 16:19 -
11@axtavt: I think it's a perfectly valid real-world example if
initializedis simply being used to ensure that one and only one thread will invoke theinitialize()method. Obviouslyinitializedbeing true doesn't mean that initialization has definitely completed in this case, so maybe a slightly different term would be better here. Again, it depends on what it's being used for.– ColinDDec 21, 2010 at 16:24 -
23you would need 2 booleans for initStarted and initCompleted, then the first thread sets initStarted and calls initialise(), the rest wait until initCompleted is true.– MartinDec 21, 2010 at 17:32
-
4@Bozho - reads and writes to boolean fields are atomic right?, Now, volatile gives me the latest value of the boolean field. So, effectively, wouldn't
volatile booleanbe same asAtomicBoolean?. Jul 30, 2014 at 14:29 -
4@TheLostMind I'm pretty late to the party, but what you would miss are functionalities like
compareAndSet, which are effectively not implementable without some kind of synchronization– gcaliSep 1, 2015 at 14:58
Here is the notes (from Brian Goetz book) I made, that might be of help to you
AtomicXXX classes
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.
-
3
There are two main reasons why you can use an atomic boolean. First it's mutable, you can pass it in as a reference and change the value that is 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
public final class SomeThreadSafeObject{
public void doSomeWork(AtomicBoolean b){
b.set(true);
}
}
More importantly though, it's 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.
-
5For the love of god, that was only to show the mutability of the object itself. I specifically wrote that for demonstration purposes. Dec 21, 2010 at 16:24
-
And further more, if that was ALL that was happening then yes, it will always return true Dec 21, 2010 at 16:25
-
2I think that only Volatile is not enough. Think about a situation in which two threads that read and write the same value directly from the main memory, there isn't any sync between those threads - hance concurrency problems might arise. Mar 24, 2015 at 20:31
-
1You wrote in the answer "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", I think that volatile won't be enough. Mar 24, 2015 at 21:39
-
1You're right it wouldn't be enough for atomic set then check operations, though there wasn't enough context from the OP to make that assumption. To say, volatile might not be enough is always true depending on the situation of course. Mar 24, 2015 at 21:54
The AtomicBoolean class gives you a boolean value that you can update atomically. Use it when you have multiple threads accessing a boolean variable.
The java.util.concurrent.atomic package overview gives 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 Practice by Brian Goetz.
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.
volatile booleanvsAtomicBoolean: stackoverflow.com/questions/3786825/…