Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Concurrency

    ThreadLocal, Immutability and the Bug Checklist

    private static final ThreadLocal<SimpleDateFormat> FORMAT —

    Chapter 12 of 123 min read

    ThreadLocal — a variable with a separate copy per thread#

    Java
    private static final ThreadLocal<SimpleDateFormat> FORMAT = ThreadLocal.withInitial(
        () -> new SimpleDateFormat("yyyy-MM-dd")
    ); // SimpleDateFormat isn't thread-safe

    Each 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:

    1. Don't share — each thread works on its own data and results are combined at the end (Operating Systems Ch 8).

    2. Share only immutable objects — records, List.of, Strings (Classes, Objects and Memory Ch 5). Nothing to lock.

    3. Use concurrent building blocks — ConcurrentHashMap compound methods, atomics, BlockingQueue.

    4. Lock yourself — synchronized / ReentrantLock, as small as possible, in a consistent order.

    The bug checklist — go through it for any concurrent code#

    BugSymptomPrevention
    race condition / lost updatewrong totals, different every runatomics, locks, compound CHM methods (Ch 3, 5, 8)
    check-then-actdouble-spending, duplicate insertsCAS loops, putIfAbsent/compute, locks (Ch 5, 8)
    visibilitya thread never sees a flag changevolatile, locks, concurrent collections (Ch 4)
    deadlockeverything freezes; jstack reports itglobal lock order, tryLock with timeout (Ch 6)
    livelock / starvationbusy but no progress / one thread never runsback-off with randomness, fair locks
    thread leakthread count climbs; JVM won't exitshut down executors; try-with-resources (Ch 2)
    unbounded queuememory grows under load until OOMbounded queues + rejection/backpressure (Ch 2, 7)
    blocking the common poolparallel streams and async tasks crawlcustom executors for I/O (Ch 10)
    missing timeoutthreads hang on a dead dependencytimeouts 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.