views:

305

answers:

5

What does AtomicBoolean do that a volatile boolean cannot achieve?

+10  A: 

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

nanda
+2  A: 

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.

gasan
+1  A: 

Atomic is for threading and it basically says, this operation is done in 1 machine cycle. Meaning if you have several threads, you don't get a problem if multiple of them are changing it at the same time.

Margus
+7  A: 

They are just totally different. I will show the difference for integers:

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

If two threads call the function parallely, "i" might be 5 afterwards, since the code will be compiled like this (except you cannot synchronize on int):

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

If you use an AtomicInteger and getAndAdd(int delta), you can be sure that the result will be 10.

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.

Arian
+2  A: 

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