Search code examples
javaatomicvolatile

Wwhat's the difference between Volatile variable vs Atomic variable?


Are they the same if we just considered the get/set methods? Or to say, are the following two pieces of code equivalent?

private volatile boolean a;
public boolean isA(){
    return a;
}
public void setA(boolean a){
    this.a = a;
}


private AtomicBoolean a;
public boolean isA(){
    return a.get();
}
public void setA(boolean a){
    this.a.set(a);
}

Solution

  • The advantage of the Atomic* classes are their atomic methods like 'getAndSet()' or 'compareAndSet()' which would otherwise require locking.

    If you don't have any compound actions, e.g. just want to ensure that all threads see the latest value of 'a', then volatile is sufficient.