Multithreading

Many hands, one counter, zero surprises. Thread lifecycle, race conditions, synchronized and volatile, executors, locks, atomics, CompletableFuture and deadlocks.

Topics in this section

Thread, Runnable & Callable

A Runnable is a job card with no box for a result. A Callable is a job card with a result box, and permission to report a problem. A Thread is a worker you'd hire yourself — but usually you hand job cards to an agency (an ExecutorService) instead.

The thread lifecycle

A thread's life story: born (NEW), ready to work (RUNNABLE), stuck outside a locked door (BLOCKED), waiting for someone to call (WAITING), napping with an alarm set (TIMED_WAITING), and retired (TERMINATED).

Race conditions & synchronized

Two cashiers share one sales notebook. Both read “10”, both write “11”. One sale just vanished. `synchronized` hands out a single pen: only the cashier holding it may read and write.

volatile & visibility

Each thread may be reading its own sticky-note copy of a variable from the CPU cache. `volatile` says “always read the whiteboard, never your sticky note.” It fixes *seeing* changes, not *coordinating* them: two threads can still write at once.

Atomics & compare-and-swap

Compare-and-swap is editing a shared doc with a rule: “only save if nobody changed it since I opened it.” If someone did, you re-read and try again. No locks, and no queue.

ExecutorService & thread pools

A thread pool is a kitchen with a few permanent chefs and a ticket rail. A new order goes to a free chef, otherwise onto the rail. Only when the rail is full do you call in temporary chefs — and if they're busy too, the order is turned away.

Each topic pairs a plain-language explanation with code, interview questions, and related practice where available.