Card 08/ 09

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 four fields
The field and how it is used
1boolean shutdown, written once by a signal handler and read by every worker loop
2long requestsHandled, incremented by every request thread
3final Map<String, Session> sessions, put into and read by many threads
4long balance and long lastMovement, which must always agree with each other
What each of the four needs
Each field, what it needs, and why
NeedsWhy
1volatileWritten whole, never computed from itself — visibility is the only problem
2An AtomicLongRead, add, write back — volatile would make it visible and still lose updates
3A ConcurrentHashMapfinal publishes the reference safely; the map's own contents still need a safe implementation
4A lock, held across both writesTwo 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.