Thread-Safe Design
Build classes that are safe by design: confine data, prefer immutability, hand work over through a blocking queue, and run tasks on a pool.
Safe by design, not by patching
The previous lesson fixed single bugs with locks. Better is to design so that most code needs no lock at all. In order of preference:
| Strategy | Idea | Locks needed |
|---|---|---|
| Confine | Each thread owns its data (local variables, one object per thread) | None |
| Immutable | Shared data that never changes after creation | None |
| Guarded | Shared mutable data behind a lock or a thread-safe class | Yes, kept small |
A class is thread-safe when it behaves correctly no matter how threads call it, without extra locking by the caller. Look for the first two options before reaching for the third.
1 of 6