Card 07/ 09
All 9 cards
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.
| Tool | Makes writes visible | Makes an operation atomic | Costs |
|---|---|---|---|
volatile | Yes | No | Almost nothing |
synchronized | Yes | Yes, for the whole block | A lock; other threads wait |
AtomicInteger and friends | Yes | Yes, for one variable | Very little; no waiting |
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.