Skip to content

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

    Java / Concurrency

    Quick Reference

    Glossary and cheat sheet for Concurrency — the page to reread before an interview.

    Extra: Reference7 min read

    Glossary#

    TermPlain meaningChapter
    Thread / Runnable / Callablea thread / its work / work that returns a value1, 2
    start vs runnew thread vs plain call1
    NEW / RUNNABLE / BLOCKED / WAITING / TIMED_WAITING / TERMINATEDthread states1
    interrupt / InterruptedExceptionpolite stop request / how waiting code receives it1
    daemon threaddoesn't keep the JVM alive1
    thread pool / ExecutorService / Futurereusable workers / its interface / a pending result2
    ThreadPoolExecutor: core / max / queue / rejectionpool tuning parameters2
    backpressureslowing producers instead of piling up work2, 7
    monitor / synchronizedevery object's built-in lock / using it3
    reentrantthe holder can re-acquire the lock3
    visibility / reorderingseeing other threads' writes / instructions moved for speed4
    Java Memory Model / happens-beforerules for cross-thread visibility / the guarantee relation4
    volatilevisibility + ordering for one variable, not atomicity4
    double-checked lockinglazy init with two checks + volatile4
    CAS / atomic classescompare-and-swap / lock-free AtomicInteger etc.5
    LongAdder / ABAcontention-friendly counter / value changed and changed back5
    ReentrantLock / tryLock / fairness / Conditionexplicit lock / try without waiting / FIFO access / wait-signal6
    read-write lockmany readers or one writer6
    jstackprints thread dumps, detects deadlocks6
    producer–consumer / BlockingQueue / poison pillpattern / waiting queue / stop signal7
    wait / notify / spurious wakeuplow-level waiting / waking / waking for no reason7
    ConcurrentHashMap / compound atomic opsthread-safe map / merge, compute, putIfAbsent8
    check-then-actnon-atomic sequence of safe calls8
    CopyOnWriteArrayList / ConcurrentSkipListMapread-mostly list / concurrent sorted map8
    CountDownLatch / Semaphore / CyclicBarrierwait for n events / limit concurrency / group rendezvous9
    CompletableFuture / thenApply / thenCompose / thenCombine / exceptionally / orTimeoutasync pipeline pieces10
    common poolshared default ForkJoinPool10
    platform thread / virtual thread / carrier / pinningOS thread / JVM thread / its host / stuck to the host11
    ThreadLocalper-thread copy of a variable12

    Cheat Sheet#

    Pick the tool

    Output
      one flag, many readers          volatile
      counter / single value          AtomicInteger/Long (LongAdder for hot counters)
      multi-step invariant            synchronized (default) / ReentrantLock (tryLock, timeout, fairness)
      mostly reads, rare writes       ReadWriteLock / CopyOnWriteArrayList
      shared map                      ConcurrentHashMap + merge / compute / computeIfAbsent
      hand work between threads       BlockingQueue (bounded)
      limit concurrent use            Semaphore
      wait for n things               CountDownLatch
      async fan-out + combine         CompletableFuture with your own executor + orTimeout
      many blocking I/O tasks         virtual threads (Java 21)
      CPU-bound parallel work         fixed pool ≈ cores

    Templates

    Java
    try (var pool = Executors.newFixedThreadPool(n)) { Future<T> f = pool.submit(callable); f.get(); }
    lock.lock(); try { ... } finally { lock.unlock(); }
    while (true) { int cur = a.get(); if (!ok(cur)) break; if (a.compareAndSet(cur, next(cur))) break; }
    sem.acquire(); try { callApi(); } finally { sem.release(); }
    synchronized (lock) { while (!condition) lock.wait(); ...; lock.notifyAll(); }
    CompletableFuture.supplyAsync(task, executor).thenApply(f).exceptionally(ex -> fallback).orTimeout(2, SECONDS).join();
    try (var ex = Executors.newVirtualThreadPerTaskExecutor()) { ex.submit(blockingTask); }

    Rules

    Output
      start(), not run() · always shut down executors · bounded queues in production
      same lock for all access · unlock in finally · consistent lock order · short critical sections
      thread-safe calls don't compose → use compound atomic methods
      volatile ≠ atomic · wait() in a while loop · never swallow InterruptedException
      timeouts on every external call · custom executor for blocking async work
      virtual threads: I/O-bound only, don't pool, semaphore for scarce resources, avoid synchronized+blocking (Java 21)

    Try This Yourself#

    1. See the invisible flag. Run the plain vs volatile flag experiment from Ch 4. Then replace volatile with reading the flag inside a synchronized getter — does the loop stop? Explain with happens-before.

    2. Race, then fix it three ways. Eight threads incrementing a shared int 100,000 times each: plain (wrong), synchronized (right), AtomicInteger (right), LongAdder (right). Time all four.

    3. Build a rate-limited AI client. Use a Semaphore(3) and a virtual-thread executor to run 50 fake "AI calls" (sleep(200)) and record the maximum concurrency seen. Add orTimeout so any call over 500 ms falls back to a cached answer.

    4. Deadlock on purpose. Write the two-account transfer from Operating Systems Ch 9 with synchronized, make it deadlock, run jstack <pid> to see "Found one Java-level deadlock", then fix it with a consistent lock order by account ID.