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
- 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.
- Create threads with
Thread+Runnable(no result) or submit aCallable(returns a value, can throw checked exceptions) to anExecutorService. Prefer executors over raw threads. start()creates a new thread that callsrun(). Callingrun()directly just runs it on the current thread. Starting a thread twice throwsIllegalThreadStateException.- 6 states:
NEW,RUNNABLE,BLOCKED(waiting for a monitor),WAITING,TIMED_WAITING,TERMINATED.sleepkeeps locks;waitreleases the monitor. - Interruption is cooperative:
interrupt()sets a flag, and blocking calls throwInterruptedExceptionand clear it. Restore it withThread.currentThread().interrupt()if you can't handle it. - A race condition is when the result depends on thread timing.
count++is read-modify-write, so it is not atomic. synchronizedgives mutual exclusion + visibility. It is reentrant and locks onthis, theClassobject (static) or a given object.volatilegives visibility and ordering but not atomicity. Good for flags and safe publication, not for counters.- Happens-before: unlock → later lock of the same monitor, volatile write → later read,
start()→ thread body, thread body →join()return. - Atomics (
AtomicInteger,LongAdder) use CAS (compare-and-swap) in a retry loop, so they need no lock.LongAdderwins under heavy write contention. ReentrantLockaddstryLock, timeouts, interruptible locking, fairness and multipleConditions. Alwaysunlock()infinally.- Deadlock needs 4 conditions (mutual exclusion, hold-and-wait, no preemption, circular wait). Break one, usually by global lock ordering or
tryLockwith timeout. ThreadPoolExecutororder: core threads → queue → extra threads up to max → rejection policy (defaultAbortPolicy). An unbounded queue means max size is never used.CompletableFuture:thenApplymaps,thenComposeflattens,thenCombinejoins two,allOfwaits for many; handle errors withexceptionally/handle.ConcurrentHashMap(Java 8+): CAS for empty bins,synchronizedon the bin head otherwise, bins turn into trees at 8 entries. Nonullkeys or values.- Virtual threads (final in Java 21) are cheap JVM-managed threads for blocking I/O. Don't pool them. In 21–23,
synchronizedblocking 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
mainplus 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
Threadand overriderun(): simple, but you use up your single inheritance and mix the task with the runner. - Implement
Runnable(usually a lambda) and pass it tonew Thread(r): separates what to run from how it runs. Preferred. Callable<V>hasV call() throws Exception, so it can return a value and throw checked exceptions. It runs through anExecutorServiceand returns aFuture<V>.- Java 21 adds builders:
Thread.ofPlatform().name("x").start(r)andThread.ofVirtual().start(r), plusThread.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.Statehas 6 values.RUNNABLEcovers 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 asynchronizedblock.WAITING=wait(),join(),LockSupport.park()with no timeout.TIMED_WAITING= the same with a timeout, orsleep.start()asks the JVM to create a new thread, which then callsrun(). Callingrun()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 ofstart()? - Difference between
sleep()andwait()?
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) throwInterruptedExceptionand clear the flag. isInterrupted()reads the flag. The staticThread.interrupted()reads and clears the current thread's flag.- If you catch
InterruptedExceptionand can't rethrow it, callThread.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 throwsUnsupportedOperationException.- Daemon threads (
setDaemon(true)beforestart()) are background helpers. The JVM exits when only daemon threads remain, without running theirfinallyblocks.
Interview questions
- How do you stop a thread in Java?
- What should you do when you catch
InterruptedException? isInterrupted()vsThread.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).
synchronizedmethods lockthis;static synchronizedmethods lock theClassobject;synchronized (obj)blocks lockobj. - 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 finallock object over synchronizing whole methods onthis(outside code could lock yourthis).
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,notifyandnotifyAllareObjectmethods. You must hold that object's monitor, or you getIllegalMonitorStateException.wait()atomically releases the lock and suspends the thread. When woken, it must re-acquire the lock before returning.- Always use
while (!condition) wait();, neverif. Threads can wake up spuriously, or another thread may have changed the state first. notify()wakes one arbitrary waiter;notifyAll()wakes all. PrefernotifyAllwhen waiters wait for different conditions, otherwise you can wake the wrong one and stall.- In new code, prefer higher-level tools:
BlockingQueue,CountDownLatch, orLock+Condition.
Interview questions
- Why must
wait()be called inside a synchronized block? - Why call
wait()in a loop instead of anif? notify()vsnotifyAll()?
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
volatileread always sees the latestvolatilewrite to that field, and the compiler and CPU can't reorder normal accesses across it in the unsafe direction. volatiledoes not give atomicity:volatileCount++is still a race. UseAtomicIntegeror a lock.- Good uses: stop/status flags, safe publication of an immutable object, and the instance field in double-checked locking.
- Writes to
longanddoublethat are notvolatilemay be split into two 32-bit halves (word tearing) on some JVMs;volatilemakes them atomic.
Interview questions
- What does
volatileguarantee? - Is
volatile int count; count++thread-safe? - Why does double-checked locking need
volatile? - When would you choose
volatileoversynchronized?
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 successfuljoin(). - Happens-before is transitive. That is why writing plain fields and then a volatile flag publishes all of them (piggybacking).
finalfields have a special guarantee: once the constructor finishes (andthisdid not escape), any thread sees their correct values, even without synchronization.java.util.concurrentdocuments its own edges, e.g. putting into aBlockingQueuehappens-before thetake, and work beforecountDown()happens-beforeawait()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,AtomicReferenceofferget/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/LongAccumulatorspread updates over several cells and sum them on read: much faster for hot counters, butsum()is not an atomic snapshot.- The ABA problem: a value changes A → B → A, so a CAS succeeds even though something changed.
AtomicStampedReferenceadds a version stamp to detect it.
Interview questions
- What is CAS and how do atomic classes use it?
AtomicLongvsLongAdder?- 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.
ReentrantLockis reentrant likesynchronized. Uselock(); try { … } finally { unlock(); }; forgettingunlockkeeps it locked forever.- Extras:
tryLock(),tryLock(timeout),lockInterruptibly(), a fairness option (new ReentrantLock(true)), and introspection likegetHoldCount(). 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, thenvalidate(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 ofwait/notify:await(),signal(),signalAll(). One lock can have several, e.g.notFullandnotEmpty.
Interview questions
- When would you use
ReentrantLockinstead ofsynchronized? - What is a
ReadWriteLockand when does it help? - What is an optimistic read in
StampedLock? Condition.await/signalvsObject.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:
tryLockwith 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 withThreadMXBean.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.ExecutorServiceaddssubmit(returns aFuture),invokeAll,invokeAnyand 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. ThenawaitTerminationwaits.- Since Java 19,
ExecutorServiceisAutoCloseable:close()callsshutdownand waits for all tasks, so try-with-resources works. ScheduledExecutorServiceruns tasks after a delay or periodically (scheduleAtFixedRate/scheduleWithFixedDelay). It replacesjava.util.Timer.
Interview questions
- Why use a thread pool instead of creating threads?
execute()vssubmit()?shutdown()vsshutdownNow()?- Why is
newFixedThreadPoolrisky 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, optionalThreadFactoryandRejectedExecutionHandler. - 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
keepAliveTimeidle.allowCoreThreadTimeOut(true)lets core threads time out too. - Queue choice:
SynchronousQueue(direct hand-off, grows threads), boundedArrayBlockingQueue(back-pressure), unboundedLinkedBlockingQueue(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,afterExecuteandterminatedfor metrics or MDC/context cleanup.
Interview questions
- Explain the parameters of
ThreadPoolExecutor. - In what order does
ThreadPoolExecutorhandle 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.
Futurehasget()(blocking),get(timeout),cancel,isDone. You can't attach callbacks or combine futures.CompletableFuture(Java 8) implementsFutureandCompletionStage. Start withsupplyAsync/runAsync, or create one andcomplete(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 (returnsVoid, 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 addedorTimeoutandcompleteOnTimeout. - Without an executor argument,
*Asyncmethods useForkJoinPool.commonPool(). Pass your own executor for blocking I/O.
Interview questions
- Difference between
FutureandCompletableFuture? thenApplyvsthenCompose?- 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.
HashtableandCollections.synchronizedMaplock the whole map for every call.ConcurrentHashMaplets 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
synchronizedon the first node of a bin otherwise. - Reads (
get) take no lock; node values and next pointers arevolatile. 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. nullkeys and values are not allowed:getreturningnullmust mean 'absent', since you can't check-then-get atomically.- Use the atomic compound methods:
putIfAbsent,computeIfAbsent,compute,merge. Iterators are weakly consistent: never throwConcurrentModificationException, may or may not show recent changes.
Interview questions
- How does
ConcurrentHashMapachieve thread safety in Java 8+? ConcurrentHashMapvsHashtablevssynchronizedMap?- Why doesn't
ConcurrentHashMapallow 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 (defaultInteger.MAX_VALUE), separate put and take locks.SynchronousQueue: zero capacity, eachputwaits for atake.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?
ArrayBlockingQueuevsLinkedBlockingQueue?- What is a
SynchronousQueueused 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()untilcountDown()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
CountDownLatchvsCyclicBarrier?- 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
Threadhas aThreadLocalMap.tl.get()looks up the current thread's map withtlas the key, so no synchronization is needed. - Uses: per-thread non-thread-safe helpers (old
SimpleDateFormat), request context (user id, transaction, MDC logging), Spring'sRequestContextHolderand 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.
InheritableThreadLocalcopies 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
ThreadLocaland when do you use it? - How can
ThreadLocalcause a memory leak? ThreadLocalvsScopedValue?
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) orRecursiveActionsplits work until it is small,fork()s one half, computes the other andjoin()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 andCompletableFutureasync 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?
ForkJoinPoolvsThreadPoolExecutor?- 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)orExecutors.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,sleepor aj.u.clock, 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: useReentrantLock. JDK 24 (JEP 491) removed pinning forsynchronized; 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?