Card 08/ 09
All 9 cards
ExerciseDifficulty: Advanced1 min
Four Fields: Which Needs Which
Four fields shared between threads. For each, decide what it needs — nothing, volatile, an atomic class, or a lock — and why. All four before the reveal.
| The field and how it is used | |
|---|---|
| 1 | boolean shutdown, written once by a signal handler and read by every worker loop |
| 2 | long requestsHandled, incremented by every request thread |
| 3 | final Map<String, Session> sessions, put into and read by many threads |
| 4 | long balance and long lastMovement, which must always agree with each other |
What each of the four needs
| Needs | Why | |
|---|---|---|
| 1 | volatile | Written whole, never computed from itself — visibility is the only problem |
| 2 | An AtomicLong | Read, add, write back — volatile would make it visible and still lose updates |
| 3 | A ConcurrentHashMap | final publishes the reference safely; the map's own contents still need a safe implementation |
| 4 | A lock, held across both writes | Two fields that must agree; no per-field tool can span them |
The third is the one worth pausing on. final guarantees the reference is visible to every thread once the constructor finishes, and says nothing at all about what happens inside the object it points at.
The fourth is the boundary of everything else in this topic. An atomic class covers one variable, and the moment correctness spans two fields the only tool left is a lock.