Thejava.util.concurrent.atomic
package defines classes that support atomic operations on single variables. All classes haveget
andset
methods that work like reads and writes onvolatile
variables. That is, aset
has a happens-before relationship with any subsequentget
on the same variable. The atomiccompareAndSet
method also has these memory consistency features, as do the simple atomic arithmetic methods that apply to integer atomic variables.To see how this package might be used, let's return to the
class we originally used to demonstrate thread interference:
Counter
One way to makeclass Counter { private int c = 0; public void increment() { c++; } public void decrement() { c--; } public int value() { return c; } }Counter
safe from thread interference is to make its methods synchronized, as in:
SynchronizedCounter
For this simple class, synchronization is an acceptable solution. But for a more complicated class, we might want to avoid the liveness impact of unnecessary synchronization. Replacing theclass SynchronizedCounter { private int c = 0; public synchronized void increment() { c++; } public synchronized void decrement() { c--; } public synchronized int value() { return c; } }int
field with anAtomicInteger
allows us to prevent thread interference without resorting to synchronization, as in:
AtomicCounter
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(); } }