306

What does AtomicBoolean do that a volatile boolean cannot achieve?

4
  • 22
    I was looking for a more nuanced answer to: "what are the limitations of each?". For instance, if is is a flag set by one thread and read by one or more others, there is no need for AtomicBoolean. However, as I am seeing with these answers, if thread are sharing a variable in a multiple threads can write and are acting on the result of their reads, AtomicBoolean brings CAS type non-locking operations into play. I'm learning quite a bit here, actually. Hopefully, others will benefit too.
    – JeffV
    Sep 24, 2010 at 13:59
  • 1
    possible duplicate of volatile boolean vs. AtomicBoolean
    – Flow
    Apr 7, 2014 at 12:50
  • volatile boolean will need explicit synchronization to handle race conditions, in other words, scenario like shared resource being updated (change of state) by multiple threads e.g. increment/decrement counter or flipping boolean.
    – sactiw
    Sep 16, 2017 at 4:11
  • 1

12 Answers 12

292

I use volatile fields when said field is ONLY UPDATED by its owner thread and the value is only read by other threads, you can think of it as a publish/subscribe scenario where there are many observers but only one publisher. However if those observers must perform some logic based on the value of the field and then push back a new value then I go with Atomic* vars or locks or synchronized blocks, whatever suits me best. In many concurrent scenarios it boils down to get the value, compare it with another one and update if necessary, hence the compareAndSet and getAndSet methods present in the Atomic* classes.

Check the JavaDocs of the java.util.concurrent.atomic package for a list of Atomic classes and an excellent explanation of how they work (just learned that they are lock-free, so they have an advantage over locks or synchronized blocks)

2
  • 2
    @ksl I think @teto want to describe that if only one thread modify the boolean var, we should choose volatile boolean.
    – znlyj
    Jun 19, 2016 at 8:46
  • 2
    Excellent summary. Jul 1, 2016 at 9:46
137

They are just totally different. Consider this example of a volatile integer:

volatile int i = 0;
void incIBy5() {
    i += 5;
}

If two threads call the function concurrently, i might be 5 afterwards, since the compiled code will be somewhat similar to this (except you cannot synchronize on int):

void incIBy5() {
    int temp;
    synchronized(i) { temp = i }
    synchronized(i) { i = temp + 5 }
}

If a variable is volatile, every atomic access to it is synchronized, but it is not always obvious what actually qualifies as an atomic access. With an Atomic* object, it is guaranteed that every method is "atomic".

Thus, if you use an AtomicInteger and getAndAdd(int delta), you can be sure that the result will be 10. In the same way, if two threads both negate a boolean variable concurrently, with an AtomicBoolean you can be sure it has the original value afterwards, with a volatile boolean, you can't.

So whenever you have more than one thread modifying a field, you need to make it atomic or use explicit synchronization.

The purpose of volatile is a different one. Consider this example

volatile boolean stop = false;
void loop() {
    while (!stop) { ... }
}
void stop() { stop = true; }

If you have a thread running loop() and another thread calling stop(), you might run into an infinite loop if you omit volatile, since the first thread might cache the value of stop. Here, the volatile serves as a hint to the compiler to be a bit more careful with optimizations.

16
  • 101
    -1: you're giving examples but not really explaining the difference between a volatile and an Atomicxxxx.
    – Jason S
    Feb 2, 2011 at 14:56
  • 91
    The question is not about volatile. The question is about volatile boolean vs AtomicBoolean.
    – dolmen
    Sep 6, 2012 at 17:26
  • 38
    -1: the question specifically asked about boolean, which is a unique case compared to the other data types and should be explained directly. Dec 31, 2012 at 19:48
  • 8
    @sgp15 It has to do with synchronization as of Java 5. Sep 10, 2013 at 10:36
  • 7
    If the boolean value is read by many threads, but written by only one thread, then volatile boolean is sufficient. If there are also many writers, you may need AtomicBoolean.
    – StvnBrkdll
    Oct 14, 2016 at 22:50
61

You can't do compareAndSet, getAndSet as atomic operation with volatile boolean (unless of course you synchronize it).

3
  • 7
    This is true, but wouldn't this be a pretty rare requirement for a boolean?
    – Robin
    Mar 28, 2014 at 18:22
  • 2
    @Robin think about using it to control a lazy invocation of a initialization method. Nov 16, 2016 at 23:12
  • 1
    Actually I would think this is one of the main use cases.
    – fool4jesus
    Jun 16, 2020 at 12:51
47

AtomicBoolean has methods that perform their compound operations atomically and without having to use a synchronized block. On the other hand, volatile boolean can only perform compound operations if done so within a synchronized block.

The memory effects of reading/writing to volatile boolean are identical to the get and set methods of AtomicBoolean respectively.

For example the compareAndSet method will atomically perform the following (without a synchronized block):

if (value == expectedValue) {
    value = newValue;
    return true;
} else {
    return false;
}

Hence, the compareAndSet method will let you write code that is guaranteed to execute only once, even when called from multiple threads. For example:

final AtomicBoolean isJobDone = new AtomicBoolean(false);

...

if (isJobDone.compareAndSet(false, true)) {
    listener.notifyJobDone();
}

Is guaranteed to only notify the listener once (assuming no other thread sets the AtomicBoolean back to false again after it being set to true).

4
  • @android developer My answer doesn't mention anything about performance! Can you clarify which part of the answer made you think that? Typically volatile variables are implemented with memory fencing instructions if they exist on the CPU and not with synchronisation/locks. This is similar to how AtomicXXX classes use compare-and-set or load-linked store-conditional instructions if they exist on the CPU.
    – Nam San
    Jan 13, 2022 at 7:22
  • Sorry removed. I think I wrote it to the wrong place. Anyway, which one (volatile vs Atomic) is better in terms of performance, if all you use them for is get&set (without CAS)? Jan 13, 2022 at 9:10
  • 1
    @android developer If you check the source code, you'll see that the AtomicBoolean get() method is implemented by reading a volatile int field and comparing it to 0 while the set() method is implemented by writing a 0 or 1 to the volatile int field. So the performance of the actual read or write will be very similar if not identical between AtomicBooleans and volatile booleans. The AtomicBoolean will have the overhead of the extra function call and comparison if the JIT was unable to optimise them away. If you have many then a volatile boolean will be more efficient in terms of memory and GC.
    – Nam San
    Jan 14, 2022 at 1:54
  • So it's a tiny bit better to use volatile instead, if that's the scenario. OK thanks. Jan 15, 2022 at 7:40
17

Volatile boolean vs AtomicBoolean

The Atomic* classes wrap a volatile primitive of the same type. From the source:

public class AtomicLong extends Number implements java.io.Serializable {
   ...
   private volatile long value;
   ...
   public final long get() {
       return value;
   }
   ...
   public final void set(long newValue) {
       value = newValue;
   }

So if all you are doing is getting and setting a Atomic* then you might as well just have a volatile field instead.

What does AtomicBoolean do that a volatile boolean cannot achieve?

Atomic* classes give you methods that provide more advanced functionality such as incrementAndGet() for numbers, compareAndSet() for booleans, and other methods that implement multiple operations (get/increment/set, test/set) without locking. That's why the Atomic* classes are so powerful.

For example, if multiple threads are using the following code using ++, there will be race conditions because ++ is actually: get, increment, and set.

private volatile value;
...
// race conditions here
value++;

However, the following code will work in a multi-threaded environment safely without locks:

private final AtomicLong value = new AtomicLong();
...
value.incrementAndGet();

It's also important to note that wrapping your volatile field using Atomic* class is a good way to encapsulate the critical shared resource from an object standpoint. This means that developers can't just deal with the field assuming it is not shared possibly injecting problems with a field++; or other code that introducing race conditions.

16

volatile keyword guarantees happens-before relationship among threads sharing that variable. It doesn't guarantee you that 2 or more threads won't interrupt each other while accessing that boolean variable.

3
  • 17
    Boolean (as in primitive type) access is atomic in Java. Both reads and assignments. So no other thread will "interrupt" boolean operations. Apr 14, 2011 at 12:25
  • 2
    I'm sorry but how does this answer the question? An Atomic* class wraps a volatile field.
    – Gray
    Sep 6, 2016 at 14:51
  • Aren't CPU caches the main factor for setting volatile? To ensure that the value read is actually what it was set to most recently
    – jocull
    Mar 11, 2019 at 14:52
9

A lot of the answers here are overly complicated, confusing, or just wrong. For example:

… if you have multiple threads modifying the boolean, you should use an AtomicBoolean.

That's incorrect as a general statement.

If a variable is volatile, every atomic access to it is synchronized …

That is not correct; synchronization is a separate thing altogether.

The simple answer is that AtomicBoolean allows you to prevent race conditions in certain operations that require reading the value and then writing a value that depends on what you read; it makes such operations atomic (i.e. it removes the race condition where the variable might change between the read and the write)—hence the name.

If you are just reading and writing the variable where the writes don't depend on a value you just read, volatile will work just fine, even with multiple threads.

7

Remember the IDIOM -

READ - MODIFY- WRITE this you can't achieve with volatile

3
  • 3
    Short, crispy and to the point. volatile only works in the cases where the owner thread has the ability to update the field value and the other threads can only read.
    – Arefe
    Nov 8, 2018 at 3:29
  • 2
    @ChakladerAsfakArefe Nope! As MoveFast says, the only thing you can't do is read+modify+write. So, for example, with some volatile boolean keepRunning = true; in a worker thread, two unrelated threads could call a cancel method on the worker that sets keepRunning = false;, and the worker thread will correctly pick up on the latest value written. The only thing that won't work is on the order of keepRunning = !keepRunning; because that's a read-modify-write.
    – Falkreon
    Jul 29, 2020 at 22:26
  • To clarify: You could even have an "un-cancel" method that sets keepRunning = true;. "Nothing is true, everything is permitted" :)
    – Falkreon
    Jul 29, 2020 at 22:27
7

If there are multiple threads accessing class level variable then each thread can keep copy of that variable in its threadlocal cache.

Making the variable volatile will prevent threads from keeping the copy of variable in threadlocal cache.

Atomic variables are different and they allow atomic modification of their values.

6

If you have only one thread modifying your boolean, you can use a volatile boolean (usually you do this to define a stop variable checked in the thread's main loop).

However, if you have multiple threads modifying the boolean, you should use an AtomicBoolean. Else, the following code is not safe:

boolean r = !myVolatileBoolean;

This operation is done in two steps:

  1. The boolean value is read.
  2. The boolean value is written.

If an other thread modify the value between #1 and 2#, you might got a wrong result. AtomicBoolean methods avoid this problem by doing steps #1 and #2 atomically.

4
  • 2
    "If you have only one thread modifying your boolean, you can use a volatile boolean. " Then If you use one thread, why would u need volatile (?).. You should remove first paragraph to make the answer better ..
    – minsk
    Jun 27, 2020 at 22:09
  • @minsk one thread writing, one or more threads reading. You won't run into threading problems if you follow that pattern, but it's not quite correct either; see my comments on MoveFast's answer.
    – Falkreon
    Jul 29, 2020 at 22:29
  • @Falkreon You can certainly run into problems even with that pattern. Namely visibility problems, on which 1 or more reading threads will not "see" the updated result written by the writer thread. that is in fact the problem that volatile solves. Sep 19, 2020 at 12:34
  • @CarlosTeixeira that's exactly what I mean. volatile boolean can be safely written to, just not negated; negation is a read-modify-write cycle. But just myVolatileBool = false; is threadsafe - because that's what volatile does, forces any writes to go to the same heap memory, and forces any reads to come from heap memory.
    – Falkreon
    Sep 25, 2020 at 14:37
5

Boolean primitive type is atomic for write and read operations, volatile guarantees the happens-before principle. So if you need a simple get() and set() then you don't need the AtomicBoolean.

On the other hand if you need to implement some check before setting the value of a variable, e.g. "if true then set to false", then you need to do this operation atomically as well, in this case use compareAndSet and other methods provided by AtomicBoolean, since if you try to implement this logic with volatile boolean you'll need some synchronization to be sure that the value has not changed between get and set.

-2

Both are of same concept but in atomic boolean it will provide atomicity to the operation in case the cpu switch happens in between.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.