Card 07/ 09

ComparisonDifficulty: Advanced1 min

volatile, synchronized and an Atomic Class on Two Axes

Three tools, two problems. Picking by which one you have heard of is how a volatile counter ends up in production still losing updates.

What each tool provides, and what it costs
ToolMakes writes visibleMakes an operation atomicCosts
volatileYesNoAlmost nothing
synchronizedYesYes, for the whole blockA lock; other threads wait
AtomicInteger and friendsYesYes, for one variableVery little; no waiting
java
volatile boolean stopped;                     // a flag one thread writes and others read

synchronized void transfer(long pence) { }    // several fields changed together

AtomicLong total = new AtomicLong();          // one value, incremented from many threads
total.incrementAndGet();

The decision rule. One field that is only ever read and written whole — volatile. One value that is read, computed and written back — an atomic class. Two or more fields that have to change together — synchronized, because nothing else can cover more than one variable.

The atomic classes do their work with a compare-and-set loop: read the value, compute the new one, and swap it in only if nothing changed in between. No thread ever waits, which is why they beat a lock for a single counter and cannot replace one for the money transfer.