Thejava.util.concurrent.atomicpackage defines classes that support atomic operations on single variables. All classes havegetandsetmethods that work like reads and writes onvolatilevariables. That is, asethas a happens-before relationship with any subsequentgeton the same variable. The atomiccompareAndSetmethod 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:CounterOne way to makeclass Counter { private int c = 0; public void increment() { c++; } public void decrement() { c--; } public int value() { return c; } }Countersafe from thread interference is to make its methods synchronized, as in:SynchronizedCounterFor 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; } }intfield with anAtomicIntegerallows us to prevent thread interference without resorting to synchronization, as in:AtomicCounterimport 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(); } }