PrepStack › Backend › Java Multithreading

Java Multithreading interview cheat sheet

Threads, locks, the memory model, executors, CompletableFuture and virtual threads

Java backend interviews almost always include a concurrency round. Interviewers check that you can explain why code is or is not thread-safe: race conditions, synchronized, volatile, the memory model, locks and atomics. Then they move to the tools you use daily: executors, thread pool tuning, CompletableFuture, concurrent collections and virtual threads. Read the 15-minute revision first, then switch to Quiz mode and answer out loud.

15-minute revision

  1. A process has its own memory; its threads share the heap but each has its own stack and program counter. Threads are cheaper to create and switch, but shared memory needs synchronization.
  2. Create threads with Thread + Runnable (no result) or submit a Callable (returns a value, can throw checked exceptions) to an ExecutorService. Prefer executors over raw threads.
  3. start() creates a new thread that calls run(). Calling run() directly just runs it on the current thread. Starting a thread twice throws IllegalThreadStateException.
  4. 6 states: NEW, RUNNABLE, BLOCKED (waiting for a monitor), WAITING, TIMED_WAITING, TERMINATED. sleep keeps locks; wait releases the monitor.
  5. Interruption is cooperative: interrupt() sets a flag, and blocking calls throw InterruptedException and clear it. Restore it with Thread.currentThread().interrupt() if you can't handle it.
  6. A race condition is when the result depends on thread timing. count++ is read-modify-write, so it is not atomic.
  7. synchronized gives mutual exclusion + visibility. It is reentrant and locks on this, the Class object (static) or a given object.
  8. volatile gives visibility and ordering but not atomicity. Good for flags and safe publication, not for counters.
  9. Happens-before: unlock → later lock of the same monitor, volatile write → later read, start() → thread body, thread body → join() return.
  10. Atomics (AtomicInteger, LongAdder) use CAS (compare-and-swap) in a retry loop, so they need no lock. LongAdder wins under heavy write contention.
  11. ReentrantLock adds tryLock, timeouts, interruptible locking, fairness and multiple Conditions. Always unlock() in finally.
  12. Deadlock needs 4 conditions (mutual exclusion, hold-and-wait, no preemption, circular wait). Break one, usually by global lock ordering or tryLock with timeout.
  13. ThreadPoolExecutor order: core threads → queue → extra threads up to max → rejection policy (default AbortPolicy). An unbounded queue means max size is never used.
  14. CompletableFuture: thenApply maps, thenCompose flattens, thenCombine joins two, allOf waits for many; handle errors with exceptionally / handle.
  15. ConcurrentHashMap (Java 8+): CAS for empty bins, synchronized on the bin head otherwise, bins turn into trees at 8 entries. No null keys or values.
  16. Virtual threads (final in Java 21) are cheap JVM-managed threads for blocking I/O. Don't pool them. In 21–23, synchronized blocking pins them to the carrier; JDK 24 fixed that. Structured concurrency is still a preview API.

Thread basics

Process vs thread, concurrency vs parallelism

A process is an isolated program with its own memory. Threads are paths of execution inside a process that share its heap.

  • A process has its own address space, file handles and at least one thread. Processes talk through IPC (pipes, sockets, files).
  • A thread shares the heap, static fields and open resources of its process. Each thread has its own stack, program counter and local variables.
  • Thread creation and context switching are cheaper than for processes, but one crashing thread (e.g. OutOfMemoryError) can affect the whole JVM.
  • Concurrency means several tasks make progress in overlapping time (possibly on one core). Parallelism means they actually run at the same instant on several cores.
  • Every Java platform thread maps 1:1 to an OS thread. A JVM process starts with main plus JVM threads (GC, JIT compiler, finalizer/reference handler).

Interview questions

  • What is the difference between a process and a thread?
  • Concurrency vs parallelism?
  • Which memory areas are shared between threads?

Creating threads: Thread, Runnable, Callable

Pass a Runnable (no result) to a Thread, or submit a Callable (returns a value) to an executor and get a Future.

  • Extend Thread and override run(): simple, but you use up your single inheritance and mix the task with the runner.
  • Implement Runnable (usually a lambda) and pass it to new Thread(r): separates what to run from how it runs. Preferred.
  • Callable<V> has V call() throws Exception, so it can return a value and throw checked exceptions. It runs through an ExecutorService and returns a Future<V>.
  • Java 21 adds builders: Thread.ofPlatform().name("x").start(r) and Thread.ofVirtual().start(r), plus Thread.startVirtualThread(r).
  • In real code use an ExecutorService instead of creating threads by hand: it reuses threads, bounds concurrency and handles results.

Interview questions

  • What are the ways to create a thread in Java?
  • Runnable vs Callable?
  • Why is implementing Runnable preferred to extending Thread?

Lifecycle, start vs run, join / sleep / yield

A thread goes NEW → RUNNABLE → (BLOCKED / WAITING / TIMED_WAITING) → TERMINATED, and start() is the only way to leave NEW.

  • Thread.State has 6 values. RUNNABLE covers both running and ready-to-run; Java does not separate them (and a thread blocked in socket I/O also shows as RUNNABLE).
  • BLOCKED = waiting to enter a synchronized block. WAITING = wait(), join(), LockSupport.park() with no timeout. TIMED_WAITING = the same with a timeout, or sleep.
  • start() asks the JVM to create a new thread, which then calls run(). Calling run() yourself is a normal method call on the current thread.
  • join() waits for another thread to finish, and everything it did becomes visible to you. join(ms) waits at most that long.
  • sleep(ms) pauses the current thread and keeps any locks it holds. yield() is just a hint to the scheduler and is rarely useful.

Interview questions

  • What are the thread states in Java?
  • What happens if you call run() instead of start()?
  • Difference between sleep() and wait()?

Interrupts, stopping threads & daemon threads

You stop a thread by asking it politely with interrupt(); daemon threads don't keep the JVM alive.

  • t.interrupt() sets the thread's interrupt flag. It does not stop anything by itself; the thread must check and react.
  • Blocking methods (sleep, wait, join, BlockingQueue.take, Future.get) throw InterruptedException and clear the flag.
  • isInterrupted() reads the flag. The static Thread.interrupted() reads and clears the current thread's flag.
  • If you catch InterruptedException and can't rethrow it, call Thread.currentThread().interrupt() so callers still see the request. Never swallow it.
  • Thread.stop() is deprecated and unsafe (it could leave objects half-updated); since Java 20 it just throws UnsupportedOperationException.
  • Daemon threads (setDaemon(true) before start()) are background helpers. The JVM exits when only daemon threads remain, without running their finally blocks.

Interview questions

  • How do you stop a thread in Java?
  • What should you do when you catch InterruptedException?
  • isInterrupted() vs Thread.interrupted()?
  • What is a daemon thread? Give examples.

Synchronization & the memory model

Race conditions & synchronized

When threads share mutable state without coordination, updates get lost; synchronized makes a block atomic and its writes visible.

  • A race condition is a bug where the result depends on the timing of threads. Classic forms: read-modify-write (count++) and check-then-act (if (!map.containsKey(k)) map.put(k, v)).
  • A critical section is code that touches shared state and must not run in two threads at once.
  • Every object has an intrinsic lock (monitor). synchronized methods lock this; static synchronized methods lock the Class object; synchronized (obj) blocks lock obj.
  • Entering a monitor gives mutual exclusion; exiting it flushes writes so the next thread that locks the same monitor sees them.
  • Monitors are reentrant: a thread that holds a lock can enter other code synchronized on the same lock without deadlocking itself.
  • Prefer small synchronized blocks on a private final lock object over synchronizing whole methods on this (outside code could lock your this).

Interview questions

  • What is a race condition? Give an example.
  • Synchronized method vs synchronized block?
  • What is reentrancy and why does it matter?
  • Can two threads run a static synchronized method and an instance synchronized method of the same class at the same time?

wait / notify / notifyAll

wait() releases the monitor and sleeps until another thread calls notify/notifyAll on the same object; always wait in a while loop.

  • wait, notify and notifyAll are Object methods. You must hold that object's monitor, or you get IllegalMonitorStateException.
  • wait() atomically releases the lock and suspends the thread. When woken, it must re-acquire the lock before returning.
  • Always use while (!condition) wait();, never if. Threads can wake up spuriously, or another thread may have changed the state first.
  • notify() wakes one arbitrary waiter; notifyAll() wakes all. Prefer notifyAll when waiters wait for different conditions, otherwise you can wake the wrong one and stall.
  • In new code, prefer higher-level tools: BlockingQueue, CountDownLatch, or Lock + Condition.

Interview questions

  • Why must wait() be called inside a synchronized block?
  • Why call wait() in a loop instead of an if?
  • notify() vs notifyAll()?

volatile & visibility

volatile makes every write immediately visible to other threads and prevents reordering around it, but it does not make compound actions atomic.

  • Without synchronization, a thread may never see another thread's write: values can sit in CPU caches or registers, and the JIT may hoist a read out of a loop.
  • A volatile read always sees the latest volatile write to that field, and the compiler and CPU can't reorder normal accesses across it in the unsafe direction.
  • volatile does not give atomicity: volatileCount++ is still a race. Use AtomicInteger or a lock.
  • Good uses: stop/status flags, safe publication of an immutable object, and the instance field in double-checked locking.
  • Writes to long and double that are not volatile may be split into two 32-bit halves (word tearing) on some JVMs; volatile makes them atomic.

Interview questions

  • What does volatile guarantee?
  • Is volatile int count; count++ thread-safe?
  • Why does double-checked locking need volatile?
  • When would you choose volatile over synchronized?

Java Memory Model & happens-before

The JMM defines when one thread's writes must be visible to another; the rule is the happens-before relation, not wall-clock time.

  • Compilers, the JIT and CPUs reorder instructions and cache values. The JMM (JLS chapter 17) lets them, as long as correctly synchronized programs behave as if sequentially consistent.
  • If action A happens-before B, then A's effects are visible to B and A appears ordered before B. Without such an edge, there is a data race and any stale value is allowed.
  • Key edges: program order within one thread; monitor unlock → later lock of the same monitor; volatile write → later read of that variable; Thread.start() → anything in the started thread; everything in a thread → another thread's successful join().
  • Happens-before is transitive. That is why writing plain fields and then a volatile flag publishes all of them (piggybacking).
  • final fields have a special guarantee: once the constructor finishes (and this did not escape), any thread sees their correct values, even without synchronization.
  • java.util.concurrent documents its own edges, e.g. putting into a BlockingQueue happens-before the take, and work before countDown() happens-before await() returns.

Interview questions

  • What is the Java Memory Model?
  • Explain happens-before with examples.
  • What is a data race, and is it the same as a race condition?

Atomic classes & CAS

Atomic classes update a single variable without locks by using compare-and-swap in a retry loop.

  • CAS (compare-and-swap) is a CPU instruction: 'set V to new value only if it still equals expected; tell me if it worked'. It is atomic in hardware.
  • AtomicInteger, AtomicLong, AtomicBoolean, AtomicReference offer get/set, incrementAndGet, compareAndSet, updateAndGet, accumulateAndGet.
  • CAS-based code is lock-free: a stalled thread can't block others. Under heavy contention, threads waste CPU retrying.
  • LongAdder / LongAccumulator spread updates over several cells and sum them on read: much faster for hot counters, but sum() is not an atomic snapshot.
  • The ABA problem: a value changes A → B → A, so a CAS succeeds even though something changed. AtomicStampedReference adds a version stamp to detect it.

Interview questions

  • What is CAS and how do atomic classes use it?
  • AtomicLong vs LongAdder?
  • What is the ABA problem?

Locks & liveness

Lock, ReentrantLock, ReadWriteLock, StampedLock & Condition

Explicit locks do what synchronized does plus try-lock, timeouts, interruptible waits, fairness, read/write splitting and multiple conditions.

  • ReentrantLock is reentrant like synchronized. Use lock(); try { … } finally { unlock(); }; forgetting unlock keeps it locked forever.
  • Extras: tryLock(), tryLock(timeout), lockInterruptibly(), a fairness option (new ReentrantLock(true)), and introspection like getHoldCount().
  • ReentrantReadWriteLock: many readers or one writer. Good for read-mostly data. A thread can downgrade write → read, but cannot upgrade read → write (it deadlocks).
  • StampedLock (Java 8) adds optimistic reads: read without locking, then validate(stamp); fall back to a real read lock if a write happened. It is not reentrant and has no conditions.
  • A Condition (lock.newCondition()) is the explicit-lock version of wait/notify: await(), signal(), signalAll(). One lock can have several, e.g. notFull and notEmpty.

Interview questions

  • When would you use ReentrantLock instead of synchronized?
  • What is a ReadWriteLock and when does it help?
  • What is an optimistic read in StampedLock?
  • Condition.await/signal vs Object.wait/notify?

Deadlock, livelock & starvation

Deadlock: threads wait for each other forever. Livelock: they keep reacting to each other but make no progress. Starvation: one thread never gets its turn.

  • Deadlock needs all four Coffman conditions: mutual exclusion, hold-and-wait, no preemption, circular wait. Break any one to prevent it.
  • The most practical fix is a global lock order (e.g. always lock the account with the smaller id first), which removes circular wait.
  • Other fixes: tryLock with a timeout and back-off, holding only one lock at a time, and never calling unknown (alien) code while holding a lock.
  • Livelock: threads are not blocked but keep undoing work in response to each other (two people stepping aside in a corridor). Fix with random back-off.
  • Starvation: a thread never gets CPU or a lock, e.g. due to unfair locks, priorities or a writer starved by a stream of readers. Fix with fair locks or bounded work.
  • Detect deadlocks with a thread dump (jstack <pid>, jcmd <pid> Thread.print), which prints 'Found one Java-level deadlock', or programmatically with ThreadMXBean.findDeadlockedThreads().

Interview questions

  • What is a deadlock and what conditions cause it?
  • How do you prevent deadlocks in a bank transfer between two accounts?
  • How do you detect a deadlock in production?
  • Deadlock vs livelock vs starvation?

Executors & async

ExecutorService & thread pool types

An executor separates submitting tasks from running them and reuses a pool of threads; Executors has factory methods for common pools.

  • Executor.execute(Runnable) just runs a task. ExecutorService adds submit (returns a Future), invokeAll, invokeAny and lifecycle methods.
  • Pools reuse threads, so you skip creation cost and bound how many tasks run at once, which protects memory and downstream services.
  • shutdown() stops accepting tasks and lets queued ones finish. shutdownNow() also interrupts running tasks and returns the queued ones. Then awaitTermination waits.
  • Since Java 19, ExecutorService is AutoCloseable: close() calls shutdown and waits for all tasks, so try-with-resources works.
  • ScheduledExecutorService runs tasks after a delay or periodically (scheduleAtFixedRate / scheduleWithFixedDelay). It replaces java.util.Timer.

Interview questions

  • Why use a thread pool instead of creating threads?
  • execute() vs submit()?
  • shutdown() vs shutdownNow()?
  • Why is newFixedThreadPool risky in production?

ThreadPoolExecutor parameters & rejection policies

A pool grows to core size, then queues, then grows to max size, then rejects; sizing and the queue choice decide its behaviour under load.

  • Constructor: corePoolSize, maximumPoolSize, keepAliveTime + unit, workQueue, optional ThreadFactory and RejectedExecutionHandler.
  • On execute: fewer than core threads → start a new thread. Otherwise → offer to the queue. Queue full → start a thread up to max. At max → reject.
  • Threads above core size die after keepAliveTime idle. allowCoreThreadTimeOut(true) lets core threads time out too.
  • Queue choice: SynchronousQueue (direct hand-off, grows threads), bounded ArrayBlockingQueue (back-pressure), unbounded LinkedBlockingQueue (max size is ignored), PriorityBlockingQueue.
  • Sizing rule of thumb: CPU-bound ≈ number of cores (+1). I/O-bound ≈ cores × (1 + wait time / compute time). Then measure.
  • Hooks: beforeExecute, afterExecute and terminated for metrics or MDC/context cleanup.

Interview questions

  • Explain the parameters of ThreadPoolExecutor.
  • In what order does ThreadPoolExecutor handle a new task?
  • What rejection policies exist and which would you pick?
  • How do you size a thread pool?

Future vs CompletableFuture

A Future is a handle you can only block on; a CompletableFuture lets you chain, combine and handle errors without blocking.

  • Future has get() (blocking), get(timeout), cancel, isDone. You can't attach callbacks or combine futures.
  • CompletableFuture (Java 8) implements Future and CompletionStage. Start with supplyAsync / runAsync, or create one and complete(value) yourself.
  • Chaining: thenApply (map), thenAccept (consume), thenCompose (flatMap, for a function that returns another future), thenCombine (join two independent futures).
  • Many: allOf(...) completes when all do (returns Void, so read each result after); anyOf(...) completes with the first one.
  • Errors: exceptionally (recover), handle (sees value or error), whenComplete (side effect, passes the outcome on). Java 9 added orTimeout and completeOnTimeout.
  • Without an executor argument, *Async methods use ForkJoinPool.commonPool(). Pass your own executor for blocking I/O.

Interview questions

  • Difference between Future and CompletableFuture?
  • thenApply vs thenCompose?
  • How do you handle exceptions in a CompletableFuture chain?
  • How do you call 3 services in parallel and combine the results with a timeout?

Concurrent collections & coordination

ConcurrentHashMap internals

A thread-safe hash map that locks only one bin at a time for writes and lets reads run without locks.

  • Hashtable and Collections.synchronizedMap lock the whole map for every call. ConcurrentHashMap lets many threads read and write different bins in parallel.
  • Java 7 used 16 segments (each a small locked hash table). Java 8 removed them: it uses CAS to insert into an empty bin and synchronized on the first node of a bin otherwise.
  • Reads (get) take no lock; node values and next pointers are volatile. A bin with 8+ nodes becomes a red-black tree (if the table has 64+ bins), and turns back into a list at 6.
  • Resizing is done cooperatively: threads that write during a resize help move bins, and ForwardingNodes redirect reads to the new table.
  • null keys and values are not allowed: get returning null must mean 'absent', since you can't check-then-get atomically.
  • Use the atomic compound methods: putIfAbsent, computeIfAbsent, compute, merge. Iterators are weakly consistent: never throw ConcurrentModificationException, may or may not show recent changes.

Interview questions

  • How does ConcurrentHashMap achieve thread safety in Java 8+?
  • ConcurrentHashMap vs Hashtable vs synchronizedMap?
  • Why doesn't ConcurrentHashMap allow null keys or values?

BlockingQueue & producer-consumer

A BlockingQueue makes producers wait when it is full and consumers wait when it is empty, so it handles the hand-off and the synchronization for you.

  • Four styles per operation: throw (add/remove), special value (offer/poll), block (put/take), and time out (offer(e, t, unit)/poll(t, unit)).
  • ArrayBlockingQueue: bounded, array-backed, one lock. LinkedBlockingQueue: optionally bounded (default Integer.MAX_VALUE), separate put and take locks.
  • SynchronousQueue: zero capacity, each put waits for a take. PriorityBlockingQueue: unbounded, ordered. DelayQueue: elements become available after a delay. LinkedTransferQueue: producers can wait for a consumer.
  • A bounded queue gives natural back-pressure: fast producers slow down instead of using all memory.
  • To stop consumers, send a poison pill (a special marker element) or interrupt them.

Interview questions

  • How would you implement the producer-consumer problem in Java?
  • ArrayBlockingQueue vs LinkedBlockingQueue?
  • What is a SynchronousQueue used for?

CountDownLatch, CyclicBarrier, Semaphore & Phaser

Synchronizers coordinate when threads may proceed: wait for N events, meet at a point, limit concurrent access, or run in phases.

  • CountDownLatch(n): threads await() until countDown() has been called n times. One-shot; it can't be reset. Use it for 'start when all services are ready' or 'wait until N workers finish'.
  • CyclicBarrier(n, action): n threads call await() and all wait until the last one arrives; then the optional action runs once and the barrier resets for the next round.
  • Semaphore(permits): acquire() takes a permit (waits if none), release() gives one back. It limits how many threads use a resource at once, e.g. 10 concurrent DB calls.
  • Phaser: a reusable barrier where parties can register and deregister dynamically, with numbered phases. It generalizes both latch and barrier.
  • Exchanger: two threads swap objects at a meeting point (rarely asked).

Interview questions

  • CountDownLatch vs CyclicBarrier?
  • How would you limit calls to an external API to 10 at a time?
  • Semaphore vs a lock?

ThreadLocal & memory leaks

ThreadLocal gives every thread its own copy of a variable; in thread pools you must remove() it, or data leaks between requests and memory leaks.

  • Each Thread has a ThreadLocalMap. tl.get() looks up the current thread's map with tl as the key, so no synchronization is needed.
  • Uses: per-thread non-thread-safe helpers (old SimpleDateFormat), request context (user id, transaction, MDC logging), Spring's RequestContextHolder and transaction synchronization.
  • In a pool, threads live forever, so a value set for one request is still there for the next task on that thread. Always clear in finally { tl.remove(); }.
  • Map entries use a weak reference to the key (the ThreadLocal) but a strong reference to the value. If the ThreadLocal is gone, the value stays until the thread dies or the map cleans stale entries. Classic leak: app-server classloader leaks on redeploy.
  • InheritableThreadLocal copies values to child threads at creation, but not to pool threads that already exist.
  • With virtual threads (millions of threads), heavy ThreadLocals cost memory. Scoped values (ScopedValue, final in JDK 25) are the immutable, bounded-lifetime alternative.

Interview questions

  • What is ThreadLocal and when do you use it?
  • How can ThreadLocal cause a memory leak?
  • ThreadLocal vs ScopedValue?

Parallelism & modern Java

ForkJoinPool & parallel streams

ForkJoinPool splits big CPU-bound tasks into subtasks and balances them with work stealing; parallel streams run on its common pool.

  • Divide and conquer: a RecursiveTask<V> (returns a value) or RecursiveAction splits work until it is small, fork()s one half, computes the other and join()s.
  • Work stealing: each worker has its own deque. It pushes and pops its own tasks at one end (LIFO); idle workers steal from the other end (FIFO) of busy workers' deques.
  • ForkJoinPool.commonPool() is shared by the whole JVM: parallel streams and CompletableFuture async methods with no executor. Its default parallelism is cores − 1 (the caller thread also helps).
  • Parallel streams help for large, CPU-heavy, easily split sources (arrays, ArrayList, IntStream.range) with stateless, non-interfering operations. They hurt for small data, LinkedList, I/O, or order-sensitive ops.
  • Never block (I/O, locks) inside common-pool tasks: it starves every other user of the pool.

Interview questions

  • What is work stealing?
  • ForkJoinPool vs ThreadPoolExecutor?
  • When should you not use parallel streams?

Virtual threads (Java 21), pinning & structured concurrency

Virtual threads are cheap JVM-scheduled threads that unmount from their carrier while blocked, so plain blocking code scales to huge numbers of concurrent tasks.

  • Final in Java 21 (JEP 444). Create with Thread.ofVirtual().start(r), Thread.startVirtualThread(r) or Executors.newVirtualThreadPerTaskExecutor().
  • The JVM runs virtual threads on a small pool of carrier platform threads (a ForkJoinPool, about one per core). When a virtual thread blocks on I/O, sleep or a j.u.c lock, its stack is saved to the heap and the carrier runs another one.
  • They make I/O-bound thread-per-request code scale without reactive callbacks. They do not make CPU-bound code faster.
  • Don't pool them; create one per task. Limit access to scarce resources with a Semaphore, not a small pool.
  • Pinning: in JDK 21–23 a virtual thread that blocks inside synchronized (or a native frame) stays stuck on its carrier. Fix there: use ReentrantLock. JDK 24 (JEP 491) removed pinning for synchronized; native/JNI frames still pin.
  • Structured concurrency (StructuredTaskScope) treats a group of subtasks as one unit: if one fails, the others are cancelled, and none outlive the scope. It is still a preview API (preview since 21; the API was reshaped in JDK 25; sixth preview in JDK 26) and needs --enable-preview.

Interview questions

  • What are virtual threads and how do they differ from platform threads?
  • When do virtual threads not help?
  • What is pinning and how do you avoid it?
  • What is structured concurrency and is it production-ready?