1

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);
}
Coren
  • 5,517
  • 1
  • 21
  • 34
elmar
  • 41
  • 1
  • 6

1 Answers1

7

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.

drobert
  • 1,230
  • 8
  • 21
  • 3
    And just to make it explicit, note that `++` and `--` are compound actions, even though they're very succinct in the code. – yshavit Mar 15 '12 at 16:08