Skip to content

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

    Java / Concurrency

    The Whole Story

    The whole module retold as one story — no new facts, a fast revision of Concurrency.

    Extra: Revision3 min read

    More cooks in the same kitchen means more dishes at once — Java threads created with a Runnable, launched with start() (never run()), waited for with join(), and stopped politely with interruption (Ch 1). Because cooks are expensive, real kitchens keep a thread pool — a fixed team and an order rail — handing back Futures, sized to the core count for CPU work and much larger for waiting work, with bounded queues so overload pushes back instead of exhausting memory (Ch 2).

    Sharing the kitchen needs rules. synchronized hangs one key by every object's door, giving mutual exclusion and visibility (Ch 3). Visibility is not automatic: under the Java Memory Model each colleague may keep reading a stale notepad, and we watched a thread loop forever on a flag that had already changed — until volatile, a happens-before edge, made the write visible; but volatile never makes count++ atomic (Ch 4). Compare-and-swap updates a single value without locks — "change 10 to 9 only if it still says 10" — which granted exactly 3 of 8 requests for 3 credits (Ch 5). ReentrantLock adds the smarter keys: tryLock, timeouts and read-write splitting, which let two deadlocked threads give up instead of freezing (Ch 6).

    Work flows between threads through a BlockingQueue — the bakery shelf where a full shelf holds bakers back — the producer–consumer pattern with built-in backpressure (Ch 7). Shared maps must be ConcurrentHashMap, which locks single buckets; yet even it lost updates to a get-then-put sequence, while its atomic merge was exact every time (Ch 8). Latches, semaphores and barriers coordinate groups — capping AI calls at two at once (Ch 9). CompletableFuture describes whole asynchronous plans — fan out, combine, fall back, time out — on an executor you choose (Ch 10). And Java 21's virtual threads give every waiting task its own cheap thread, turning 5.2 seconds into 0.19 for ten thousand waits, as long as the work is I/O-bound (Ch 11). Above all of it sits one strategy: don't share, or share only immutable data — and a checklist for everything else (Ch 12).

    Next, Inside the JVM opens the JVM itself: how classes load, how memory is laid out, and how the garbage collector keeps it all running.