A thread is an independent call stack the JVM schedules. Concurrency bugs are almost never “I forgot a Thread.start.” They are races (check-then-act), visibility (stale reads), and deadlocks (lock order).
Mental model: without a happens-before edge, there is no guarantee another thread sees your writes — even to a boolean. The CPU and compiler may reorder. synchronized, volatile, lock release/acquire, thread start/join, and concurrent collection internals create those edges.
First design: do not share. Confine the mutable object to one thread. If you must share, share an immutable object or a concurrent collection / synchronized API with a documented lock story.
ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor(); // Java 21
ExecutorService cpu = Executors.newFixedThreadPool(nCpus);
try {
Future<Integer> f = cpu.submit(() -> compute());
int v = f.get(2, TimeUnit.SECONDS);
} finally {
cpu.shutdown();
cpu.awaitTermination(5, TimeUnit.SECONDS);
}
| Tool | Use |
|---|---|
new Thread(runnable).start() | Rare. You own lifecycle, naming, and errors. Prefer a pool. |
| Fixed / cached thread pool | Bounded concurrency for blocking work (fixed) or short tasks (cached can explode — prefer ThreadPoolExecutor with a bound queue). |
newVirtualThreadPerTaskExecutor (21) | Huge numbers of blocking tasks. Do not pool virtual threads “for reuse” the old way — they are cheap to start. |
ForkJoinPool.commonPool | Parallel streams and some CompletableFuture async methods. Do not block it with I/O. |
Future.get (wraps in ExecutionException). An uncaught exception on a raw Thread hits the uncaught-exception handler and the thread dies.Thread.stop is gone/unsafe. Cooperate with interrupts and Future.cancel(true).Virtual threads (Java 21): JVM-scheduled, cheap blocking. Still honour happens-before. Do not pin them (long synchronized around blocking I/O, or native calls). Prefer ReentrantLock if you must lock around blocking on 21+.
private final Object lock = new Object();
private int count;
void inc() {
synchronized (lock) { count++; }
}
int get() {
synchronized (lock) { return count; }
}
synchronized instance method locks this; static locks the Class. Prefer a private lock so callers cannot enter your critical section.volatile gives visibility and a happens-before on that variable. It does not make count++ atomic. Use AtomicInteger for independent counters.ReentrantLock: timed lock, interruptible lock, multiple condition variables. Always unlock in finally. Try-with-resources does not lock/unlock for you (unless you write an adapter).ReadWriteLock helps when reads dominate and you measured contention — it is not free.Deadlock: thread A holds L1 waits L2; B holds L2 waits L1. Fix: one lock-order; or lock coarsening; or avoid nested locks. Detect with thread dumps (jstack).
The JMM is not “eventual consistency.” Without a happens-before edge, a thread may loop forever on while (!ready) even after another thread set ready = true (the field is not volatile).
Happens-before (revision list):
// Incorrect
boolean ready = false;
int payload;
// thread A
payload = 42; ready = true;
// thread B
while (!ready) {}
use(payload); // payload may still be 0; loop may never see ready
// Correct — volatile ready, or both under the same lock, or AtomicInteger / CHM
long and double writes are not required to be atomic unless volatile (torn reads). Use volatile or AtomicLong for shared 64-bit values.
CompletableFuture is a promise you can complete, chain, and combine. Prefer it over raw Thread for asynchronous pipelines on 17–21.
CompletableFuture<String> f = CompletableFuture
.supplyAsync(() -> fetch(), ioPool)
.thenApply(this::parse)
.orTimeout(2, TimeUnit.SECONDS); // Java 9+
String body = f.join(); // unwraps CompletionException
supplyAsync without an executor uses the common ForkJoinPool — do not block there.thenApply vs thenApplyAsync: the former may run on the completing thread. Be explicit when it matters.get throws checked Exception; join throws unchecked CompletionException.whenComplete / exceptionally at the end of a chain you fire-and-forget, or you lose errors.orTimeout) complete exceptionally."literal" (interned — you lock a global).++ is atomic. Assuming HashMap is fine “because we only put during startup” while another thread gets.// Incorrect — lock on interned String
synchronized ("LOCK") { }
// Correct
private final Object lock = new Object();
synchronized (lock) { }
~ Good luck with your revision! ~