Atomic operation - An action that effectively happens all at once or not at all Ex: java.util.concurrent.atomic.AtomicInteger
Mutual exclusion - Prevents simultaneous access to a shared resource Ex: synchronized
With mutual exclusion approach, SynchronizedCounter
is thread safe,
class SynchronizedCounter {
private int c = 0;
public synchronized void increment() {
c++;
}
public synchronized void decrement() {
c--;
}
public synchronized int value() {
return c;
}
}
With atomic variable approach, AtomicCounter
is thread safe,
import java.util.concurrent.atomic.AtomicInteger;
class AtomicCounter {
private AtomicInteger c = new AtomicInteger(0);
public void increment() {
c.incrementAndGet();
}
public void decrement() {
c.decrementAndGet();
}
public int value() {
return c.get();
}
}
1) In the above code, Why is atomic variable approach better than mutual exclusion approach?
2) In general, Is the goal of mutual exclusion & atomic variable approach, not the same?