Part 5 of 6 · 4 min read
Thread-safe classes
Four ways to get safety.
Designing a thread-safe class
JCIP calls a class thread-safe when it stays correct under use by many threads, however they are scheduled, and callers need add no coordination of their own. The class owns the safety.
There are four main ways to achieve it, listed here in the order to try them.
- Do not share. Keep data inside one thread. A local variable is private to its thread. This is confinement. JCIP also describes instance confinement: hide a non-thread-safe object inside a class and let only that class touch it, always under one lock.
- Share only immutable data. Value objects (module 2) need no locks.
- Delegate to a thread-safe component. A class whose only mutable state is one
ConcurrentHashMaporAtomicIntegercan rely on it. Care is needed if two such components must change together, because each is safe alone and the pair is not. - Guard with a lock. For shared mutable state with an invariant that spans several fields, one lock must cover all of them.
The money transfer shows the pair problem and a second danger: deadlock. Moving money between two accounts changes two balances, so both must be held while the move happens.
static void transfer(Account from, Account to, long amt) {
Account first = from.id < to.id ? from : to;
Account second = first == from ? to : from;
synchronized (first) { synchronized (second) {
from.add(-amt); to.add(amt);
} }
}
Two threads move money in opposite directions between the same two accounts. If each took the locks in the order of "from, then to", thread A would hold account 1 and wait for account 2, while thread B held account 2 and waited for account 1. Neither can proceed. This is a deadlock. JCIP shows that lock-ordering deadlock cannot happen when every thread takes its locks in one agreed order across the whole program. The code above always locks the lower id first. After two threads each make 20000 round trips of 1 rupee (made up), both balances end at 1000, and the program finishes.
JCIP adds the advice of open calls: call other objects' methods with no lock held where possible, since a call into unknown code with a lock held can create a deadlock you cannot see.
Last, write the policy down. JCIP asks for two kinds of notes: what the class promises its clients about threads, and how it achieves that, for the people who maintain it. EJ Item 82 says the same. A one-line comment such as "thread-safe; all state guarded by this" is the minimum. Many standard classes, such as HashMap, are not thread-safe, and the documentation is how a reader learns that.
Deadlock
A deadlock is a stalemate where each of two or more threads holds a lock the other needs, so none can continue.
Example: two transfers in opposite directions, each holding one account and waiting for the other.
Common mistake
Using a thread-safe collection and then doing a check followed by an action in two calls. Each call is safe, but the pair is not. Use one atomic method such as putIfAbsent or merge, or hold a lock around both.
Interview angle
Answer in your head first, then open it.
How do you stop two users booking the same seat?
Make check-and-reserve one atomic step, under one lock or with an atomic map operation, and say what the second user sees.
What is a deadlock and how do you prevent it?
Threads waiting on each other's locks. Always take locks in one fixed order, hold them briefly, and make open calls.
What does volatile do?
It makes writes visible to other threads. It does not make compound actions atomic.
Check yourself: 1. Which of the four ways needs the least thought? 2. Why does the transfer code lock the lower id first? 3. What should be written down for each shared class?
Words you will meet
| Word | Meaning |
|---|---|
| Race condition | A bug whose outcome depends on the timing of threads |
| Atomic | Happening as one unbroken step |
| Guarded | Protected by a named lock at every access |
| Visibility | Whether one thread sees another thread's write |
| Deadlock | Threads waiting on each other's locks forever |