teacher
Sign in

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.

28 min4 interactive

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:

StrategyIdeaLocks needed
ConfineEach thread owns its data (local variables, one object per thread)None
ImmutableShared data that never changes after creationNone
GuardedShared mutable data behind a lock or a thread-safe classYes, 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