ThreadLocal — a variable with a separate copy per thread#
private static final ThreadLocal<SimpleDateFormat> FORMAT = ThreadLocal.withInitial(
() -> new SimpleDateFormat("yyyy-MM-dd")
); // SimpleDateFormat isn't thread-safeEach thread gets its own instance, so there's nothing to share and nothing to lock. Frameworks use it to carry per-request data (the current user, a
request ID for logs — Observability in Practice (coming soon)). Gotcha: in thread pools, threads are reused, so a value set for one request leaks into the next
unless you remove() it in a finally block.
The best concurrency strategy: don't share mutable state#
In order of preference:
Don't share — each thread works on its own data and results are combined at the end (Operating Systems Ch 8).
Share only immutable objects — records,
List.of, Strings (Classes, Objects and Memory Ch 5). Nothing to lock.Use concurrent building blocks —
ConcurrentHashMapcompound methods, atomics,BlockingQueue.Lock yourself —
synchronized/ReentrantLock, as small as possible, in a consistent order.
The bug checklist — go through it for any concurrent code#
| Bug | Symptom | Prevention |
|---|---|---|
| race condition / lost update | wrong totals, different every run | atomics, locks, compound CHM methods (Ch 3, 5, 8) |
| check-then-act | double-spending, duplicate inserts | CAS loops, putIfAbsent/compute, locks (Ch 5, 8) |
| visibility | a thread never sees a flag change | volatile, locks, concurrent collections (Ch 4) |
| deadlock | everything freezes; jstack reports it | global lock order, tryLock with timeout (Ch 6) |
| livelock / starvation | busy but no progress / one thread never runs | back-off with randomness, fair locks |
| thread leak | thread count climbs; JVM won't exit | shut down executors; try-with-resources (Ch 2) |
| unbounded queue | memory grows under load until OOM | bounded queues + rejection/backpressure (Ch 2, 7) |
| blocking the common pool | parallel streams and async tasks crawl | custom executors for I/O (Ch 10) |
| missing timeout | threads hang on a dead dependency | timeouts on every external call (Ch 10) |
Testing concurrent code: bugs depend on timing, so a passing test proves little. Run stress tests with many threads and many iterations, run them repeatedly, and reason with happens-before rather than hoping. Tools like jcstress (from the OpenJDK team) exist specifically for this.