301

What does AtomicBoolean do that a volatile boolean cannot achieve?

BuZZ-dEE
  • 6,075
  • 12
  • 66
  • 96
JeffV
  • 52,985
  • 32
  • 103
  • 124
  • 21
    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 '10 at 13:59
  • 1
    possible duplicate of [volatile boolean vs. AtomicBoolean](http://stackoverflow.com/questions/4876122/volatile-boolean-vs-atomicboolean) – Flow Apr 07 '14 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 '17 at 04:11
  • 1
    See also general [What is the difference between atomic / volatile / synchronized?](https://stackoverflow.com/questions/9749746/what-is-the-difference-between-atomic-volatile-synchronized) – Vadzim Oct 08 '19 at 09:34

12 Answers12

288

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)

teto
  • 4,019
  • 4
  • 21
  • 18
133

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.

Cephalopod
  • 14,632
  • 7
  • 51
  • 70
  • 101
    -1: you're giving examples but not really explaining the difference between a volatile and an Atomicxxxx. – Jason S Feb 02 '11 at 14:56
  • 1
    Please have a look at the original question. "Allow atomic modifications" is a valid answer. – Cephalopod Feb 03 '11 at 14:31
  • 90
    The question is not about `volatile`. The question is about `volatile boolean` vs `AtomicBoolean`. – dolmen Sep 06 '12 at 17:26
  • 37
    -1: the question specifically asked about boolean, which is a unique case compared to the other data types and should be explained directly. – John Haager Dec 31 '12 at 19:48
  • 3
    sgp15, volatile accesses are synchronizing actions (http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4.2), as such, they define an order for concurrent events which makes them equivalent to locking on the same monitor. – Cephalopod May 10 '13 at 10:18
  • 8
    @sgp15 It has to do with synchronization as of Java 5. – Man of One Way Sep 10 '13 at 10:36
  • So in the volatile boolean example, how would using an AtomicBoolean be any different? This would be the actual question being asked, and other than the getAndSet() method (assuming you actually needed that ability), I am not sure there is any difference. – Robin Mar 20 '14 at 21:40
  • @Robin, you can always replace a `volatile` with an Atomic*. But sometimes, it isn't necessary and you can safe some overhead. Replacing Atomics with volatile will hurt. – Cephalopod Mar 20 '14 at 22:04
  • How will it hurt? Specifically for AtomicBoolean, not Atomics in general. I would rather code to a boolean directly, as the code is much more readable than using the get/set methods of an AtomicBoolean. – Robin Mar 28 '14 at 18:21
  • 4
    `flag = !flag` on a volatile boolean is not thread-safe. If you are using *only* `get` and `set` of the atomic variable, switching should be possible though. – Cephalopod Mar 31 '14 at 20:42
  • 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 '16 at 22:50
  • 3
    The correct answer should be that it provides you a compare and set function which isn't possible with volatile boolean (without explicitly synchronizing). This answer isn't very clear. Simpler is better. I would ask OP to consider editing the answer since this is the accepted answer. – rents Mar 28 '17 at 18:41
  • This answer is just wrong in my opinion. AtomicBoolean is just a wrapper for a primitive boolean, see other answers. i.e. you want to use an object (e.g. Boolean) but you still want to mark it volatile --> use AtomicBoolean – bvdb Jun 06 '17 at 09:35
  • "They are just totally different." No, they are very similar. The docs state explicitly that compareAndSet is the whole point: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/package-summary.html – Max Barraclough Feb 23 '18 at 21:53
  • -1 because first, the questions is specifically about boolean (not integer increments). Second, Java reference reads/writes are atomic and `volatile` adds read guarantee.. so this answer with "They are just totally different" -- looks to me like the answerer doesn't understand the question – minsk Jun 27 '20 at 22:00
  • 1
    @minsk Yeah, I totally missed the question. That's why my answer immediately got accepted. – Cephalopod Jun 28 '20 at 07:29
61

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

jpaugh
  • 6,634
  • 4
  • 38
  • 90
nanda
  • 24,458
  • 13
  • 71
  • 90
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).

Nam San
  • 1,145
  • 9
  • 13
  • @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 '22 at 07: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)? – android developer Jan 13 '22 at 09: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 '22 at 01:54
  • So it's a tiny bit better to use volatile instead, if that's the scenario. OK thanks. – android developer Jan 15 '22 at 07: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.

Gray
  • 115,027
  • 24
  • 293
  • 354
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.

dhblah
  • 9,751
  • 12
  • 56
  • 92
  • 17
    Boolean (as in primitive type) access is atomic in Java. Both reads and assignments. So no other thread will "interrupt" boolean operations. – Maciej Biłas Apr 14 '11 at 12:25
  • 2
    I'm sorry but how does this answer the question? An `Atomic*` class wraps a `volatile` field. – Gray Sep 06 '16 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 '19 at 14:52
7

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.

Garret Wilson
  • 18,219
  • 30
  • 144
  • 272
7

Remember the IDIOM -

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

MoveFast
  • 3,011
  • 2
  • 27
  • 53
  • 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 08 '18 at 03:29
  • 1
    @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 '20 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 '20 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.

Amol Gaikwad
  • 71
  • 1
  • 1
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.

user2660000
  • 332
  • 2
  • 3
5

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.

Thibaut D.
  • 2,521
  • 5
  • 22
  • 33
  • 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 '20 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 '20 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. – cmhteixeira Sep 19 '20 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 '20 at 14:37
-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.