javamultithreadingjava-threadsatomicboolean

Using AtomicBoolean instead of synchronized blocks


Say I have a class with 2 instance variables and the following methods (simplified for this question):

private final Object lock = new Object();
private boolean running;

public MyClass() {
    synchronized(lock) {
        running = false;
    }
}
public void methodA() {
    synchronized(lock) {
        running = true;
    }
}
public void methodB() {
    synchronized(lock) {
        if (!running) {
            return;
        }
    }
}

I was looking at this code, and after reading about AtomicBoolean, I thought that one might fit here, especially after looking at the MyClass constructor and methodA. I wasn't too sure about methodB though.

Assuming these methods could get called by multiple threads, would the following be thread-safe?:

private AtomicBoolean running;

public MyClass() {
    running = new AtomicBoolean(false);
}
public void methodA() {
    running.set(true);
}
public void methodB() {
    if (!running.get()) {
        return;
    }
}

Will running.get() be guaranteed to see an update via running.set(true) or running.set(false) from another thread?


Solution

  • In your example, a simple volatile boolean would be enough, since you only seem to be doing atomic operations. AtomicBoolean is useful if you need the methods such as compareAndSet.

    So in answer to your question, yes, when using a volatile boolean or an AtomicBoolean, other threads will see the updates to the variable.