Threads and lifecycle
The warm-up round. Most interviews open here, and most candidates lose points not because they cannot name the thread states but because they cannot say what the JVM actually does at each transition.
- What is the difference between a process and a thread, and what does that cost you in Java? junior
- Why is
Thread.stop()deprecated, and what replaced it? junior - What actually happens when you call
interrupt()on a thread? mid - Why is swallowing
InterruptedExceptiona bug, and what is the correct handling? mid - What is the difference between a daemon thread and a user thread? junior
- What is the difference between
RunnableandCallable, and where doesFuturefit? junior - Why must you call
start()rather thanrun()? junior - What is the difference between BLOCKED, WAITING and TIMED_WAITING in a thread dump? mid
- Does
Thread.yield()do anything you can rely on? mid - Two threads, one
Thread.sleep(1000)inside asynchronizedblock. What does the other thread see? junior - Can a thread be garbage collected while it is running? senior
- What happens when a thread throws an exception nobody catches? junior
The Java memory model
The rules every other topic depends on. An answer here that says "volatile makes it thread safe" ends the interview early; an answer that can name the happens-before edge passes almost any follow-up.
- What is happens-before, in one sentence, and why does it matter? mid
- Which happens-before edges do you get for free? mid
- What does
volatileguarantee, and what does it not? junior - Why does double-checked locking need the field to be volatile? senior
- What is safe publication, and which ways of achieving it can you name? senior
- What does
finalguarantee, and what breaks that guarantee? senior - What is instruction reordering, and can you observe it from ordinary Java? senior
- Where do memory barriers come into this, and which ones does the JVM emit? senior
- Is
longanddoubleassignment atomic in Java? mid - Two threads increment a shared
inta million times each with no synchronisation. What is the final value and why? junior - What is the difference between a data race and a race condition? senior
- What does the Java memory model promise a correctly synchronized program? senior
synchronized, monitors, wait and notify
The oldest tool in the language, and still the one most production code uses. The questions here
separate people who have written synchronized from people who know what the JVM does with it.
- What exactly does
synchronizedlock? junior - Why is locking on a
Stringliteral or a boxedIntegera bug? mid - What is reentrancy, and what would break without it? mid
- Why must
wait()be called inside a loop? mid - When should you prefer
notifyAll()overnotify()? mid - Why does
wait()throwIllegalMonitorStateExceptionsometimes? junior - What is the difference between
synchronizedandReentrantLockin practice? mid - Is an uncontended
synchronizedblock expensive? senior - Can you
synchronizedon the same object from two methods and still have a race? mid - What is lock striping, and when does it stop helping? senior
Locks, conditions and AQS
Everything in java.util.concurrent.locks is one class in a trench coat: AbstractQueuedSynchronizer.
Knowing that turns a dozen separate facts into one mechanism you can reason about.
- What is
AbstractQueuedSynchronizerand which classes are built on it? senior - What does a fair lock actually do, and what does it cost? mid
- When is
ReentrantReadWriteLocka win, and when is it a trap? senior - What is optimistic reading in
StampedLock? senior - What does
Conditiongive you thatwait/notifydoes not? mid - How do you implement a timeout on acquiring a lock, and why would you? mid
- What is
LockSupport.park, and why is it better thansuspend/resume? senior - What is a spin lock, and when is spinning better than blocking? senior
- Can a thread deadlock against itself? mid
- Why is
lock()outsidetryandunlock()insidefinallythe required shape? junior
Synchronizers: latches, barriers, semaphores
The coordination primitives, and the topic with the single most predictable interview question in Java: the difference between a latch and a barrier. Knowing the whole family is what separates a memorised answer from a chosen one.
- What is the difference between
CountDownLatchandCyclicBarrier? mid - When would you use a latch as a starting gate rather than as a finish line? mid
- What does a
Semaphoreactually protect? junior - Why is
Semaphorethe right way to limit concurrency with virtual threads? senior - What is a
Phaserand when does it beat aCyclicBarrier? senior - What is an
Exchangerfor? senior - How does
CompletableFuture.allOfcompare to aCountDownLatchfor "wait for N tasks"? mid - Why must a
Semaphorerelease live in afinally, and what goes wrong if it does not? mid - Is
CountDownLatch.await()a happens-before edge? senior - Which synchroniser would you choose, and how do you decide? mid
Atomics and compare-and-swap
Lock-free code is not magic, it is one CPU instruction plus a retry loop. Interviewers use this topic to find out whether "lock-free" is a word you have read or a mechanism you can draw.
- What is compare-and-swap, and how does
AtomicInteger.incrementAndGetuse it? mid - What is the ABA problem, and how do you avoid it? senior
- Why is
LongAdderfaster thanAtomicLong, and when is it not? senior - What is false sharing, and how do you fix it? senior
- What do
getAndUpdate,updateAndGetandaccumulateAndGetdo, and what is the catch? mid - How would you write a thread-safe non-blocking counter without atomics? senior
- What is the difference between
compareAndSetandweakCompareAndSet? senior - Is
AtomicReferenceenough to make the object it points at thread safe? mid - What does "lock-free" mean, and how does it differ from "wait-free"? senior
- Can you replace
volatile boolean runningwithAtomicBoolean, and should you? junior - Does declaring an array
volatilemake its elements volatile? mid
Concurrent collections
Choosing the wrong collection is the most common real-world concurrency bug, because it does not crash. It just loses data occasionally. Interviewers ask this topic to see whether you know the difference between "thread safe" and "correct for my access pattern".
- Why is
HashtableorCollections.synchronizedMapworse thanConcurrentHashMap? junior - How does
ConcurrentHashMapwork since Java 8? senior - Why does
ConcurrentHashMapforbid null keys and values? mid - What is the iteration behaviour of a concurrent collection, and what is
ConcurrentModificationException? mid - When is
CopyOnWriteArrayListthe right choice? mid ArrayBlockingQueueorLinkedBlockingQueue, and does bounded matter? mid- What is
ConcurrentSkipListMapfor, and how does it differ fromConcurrentHashMap? mid - How would you build a thread-safe cache with
computeIfAbsent, and what is the trap? senior - What does
Collections.unmodifiableListguarantee about thread safety? mid - Is
ConcurrentHashMap.size()reliable, and what should you use instead? mid - When is a plain
HashMapbehind your own lock better thanConcurrentHashMap? senior - Many threads count words into one map. How do you make the counting correct? junior
- What is the difference between
add,offerandputon aBlockingQueue? junior
Executors and thread pools
The topic where interview answers most often come from a tutorial rather than from an incident. Every question below has cost somebody a production outage at some point.
- Walk through what
ThreadPoolExecutordoes with a submitted task. mid - Why is
Executors.newFixedThreadPoolconsidered dangerous in production? mid - How do you size a thread pool? mid
- What is the difference between
shutdown()andshutdownNow(), and how do you shut down properly? mid - What happens to an exception thrown inside a pooled task? mid
- What happens when a
ScheduledExecutorServicetask throws? senior - Which rejection policy would you choose and why? senior
- What is
invokeAllversusinvokeAny, and where doesCompletionServicefit? mid - Why name your threads, and how? junior
- Why must a
ThreadLocalbe removed in a pooled thread? senior - What is work stealing, and which executors use it? senior
- What breaks when a pooled task submits another task to the same pool and waits for it? senior
- Why is
ScheduledExecutorServicepreferred tojava.util.Timer? mid
CompletableFuture and async composition
Where interviews go once "I would use a thread pool" is settled. The trap in this topic is that everything compiles and runs, and only the thread it runs on and the exception you never see are wrong.
- What does
CompletableFutureadd overFuture? junior - What is the difference between
thenApplyandthenCompose? mid - Which thread runs your callback if you use
thenApplyrather thanthenApplyAsync? senior - Why should you pass an explicit executor to the
*Asyncmethods? mid - How do exceptions propagate through a chain, and what do
exceptionally,handleandwhenCompletedo? mid - What does
allOfreturn, and how do you collect the results? mid - Does cancelling a
CompletableFuturestop the work? senior - How do you add a timeout to a
CompletableFuture? mid - What is the difference between
join()andget()? junior - When is
CompletableFuturethe wrong tool now that virtual threads exist? senior
Fork/join and parallel streams
One method call turns a stream parallel, which is why this topic is full of code that is slower than the sequential version it replaced. Interviewers ask it to see whether you can say no.
- How does
ForkJoinPooldiffer from a fixed thread pool? mid - What is the correct shape of a
RecursiveTask? mid - What is the common pool, and why does it cause trouble? senior
- When is a parallel stream faster, and when is it slower? mid
- Why is
forEachon a parallel stream dangerous, and what should you use? mid - What does
Collectors.toConcurrentMapchange, and when isgroupingByConcurrentactually used? senior - What is a
Spliteratorand why does it matter for parallelism? senior - Can you run a parallel stream in your own pool, and should you? senior
- Why is
Stream.iteratea poor source for a parallel stream? mid - What happens if a fork/join task blocks on I/O? senior
- What does
parallelStream()change compared withstream()? junior
Virtual threads and structured concurrency
Java 21 made threads cheap. That invalidates a decade of advice, and interviewers now use this topic to find out whether a candidate has actually used them or only read the announcement.
- What is a virtual thread, and how is it scheduled? mid
- What is pinning, and what causes it? senior
- Should you pool virtual threads? mid
- When do virtual threads not help? senior
- What problem does structured concurrency solve? mid
- What are
ShutdownOnFailureandShutdownOnSuccessfor? senior - What is a
ScopedValue, and why is it preferred toThreadLocalhere? senior - How do you debug a system running a million virtual threads? senior
- Do virtual threads change how you use
synchronizedin library code? senior - Is
Thread.sleepstill a bad idea on a virtual thread? mid - What does
Executors.newVirtualThreadPerTaskExecutor().close()do? mid - Is a virtual thread faster than a platform thread? junior
Concurrency in real systems
Where core Java meets the frameworks people actually ship. These questions are the ones a backend interview reaches after the language questions are settled, and the answers are usually about which thread your code is on and which pool is about to run out.
- Which thread runs a Spring
@Asyncmethod, and what does it lose? mid - Why does
@Transactionalnot work across threads? mid - Your service has 200 HTTP threads and a pool of 10 database connections. Where is the bottleneck? senior
- Is a Spring singleton bean thread safe? junior
- What is the servlet thread model, and what does async servlet processing change? senior
- What does a reactive framework buy you over threads, and what does it cost? senior
- How do you propagate request context (trace id, user) across threads? mid
HttpClient,RestTemplateorWebClient: what concurrency questions do you ask before choosing? mid- What breaks when you use a parallel stream inside a web request? senior
- How does a connection pool interact with your thread pool, and what should you monitor? senior
- Why can one slow
@Scheduledjob delay every other scheduled job in a Spring app? mid KafkaConsumeris not thread safe. How do you process its records in parallel? senior
Deadlock, livelock and diagnostics
The half of concurrency that only exists in production. Interviewers like this topic because it cannot be answered from a tutorial: either you have read a thread dump at 3am or you have not.
- What four conditions must hold for a deadlock, and which is easiest to break? mid
- Show the classic transfer deadlock and fix it. mid
- How do you diagnose a deadlock in a running JVM? mid
- What is a livelock, and how does it differ from a deadlock? mid
- What is starvation, and what causes it in a JVM? mid
- How do you read a thread dump? What do you look for first? senior
- Your service stops responding but CPU is at zero. What is your first hypothesis? senior
- Which JDK tools do you use for concurrency problems? mid
- Why does a debugger so often make a concurrency bug disappear? mid
- A colleague reports a bug that happens once a week in production and never locally. How do you approach it? senior
- What is a deadlock, and why does it not resolve itself? junior
Patterns and antipatterns
Design judgement, which is what a senior interview is actually testing. The right answer here is usually the one that removes shared mutable state rather than the one that guards it more cleverly.
- What does thread confinement mean, and what are the three kinds? mid
- Why is immutability the strongest thread safety guarantee? junior
- What is the producer/consumer pattern and what does the queue actually provide? junior
- What is the balking pattern, and where would you use it? mid
- What is the double-checked locking antipattern really about? mid
- Why is "synchronize everything" a bad strategy? mid
- What is the thread-per-task versus task-per-thread distinction, and why did pools exist? mid
- Why should you not start a thread from a constructor? senior
- When would you choose an object pool, and when is it the wrong answer? senior
- What is the two-phase termination pattern? mid
- How do you make a class document its own thread safety? mid
- What are the thread-safe ways to write a singleton, and which would you pick? mid
Testing concurrent code
Asked far less often than it should be, and a strong differentiator when you can answer it. Most
candidates describe a test with a Thread.sleep in it, which is exactly the thing that does not work.
- Why is
Thread.sleepin a test a bug rather than a delay? mid - How do you write a test that actually creates contention? mid
- Why can a unit test not reliably catch a visibility or reordering bug? senior
- What is jcstress and when do you reach for it? senior
- How do you test that something is not possible, such as a deadlock? senior
- What makes a concurrency test flaky, and how do you deal with flakiness? mid
- How would you benchmark two concurrent implementations honestly? senior
- Can you unit test code that uses the current time or a scheduler? mid
- What static analysis helps with concurrency? mid
- What would you add to a code review checklist for concurrent code? senior
- What is the difference between
assertTimeoutandassertTimeoutPreemptivelyin JUnit 5? junior
Live coding puzzles
The whiteboard round. Each of these has a canonical solution short enough to write in ten minutes, and an obvious wrong version the interviewer is hoping you avoid.
- Print numbers 1 to 100 with two threads, one printing odd and one even, in order. mid
- Implement a bounded blocking queue with
waitandnotify. mid - Make three tasks run concurrently but print their results in a fixed order. mid
- Implement a rate limiter that allows N operations per second. senior
- Solve the dining philosophers problem without deadlock. mid
- Write a thread-safe lazily initialised cache where each key is computed once. senior
- Implement a simple
CountDownLatchyourself. senior - Write a non-blocking stack. senior
- Run a task exactly once no matter how many threads call it. mid
- Two threads, one increments and one prints a shared counter. What could go wrong, and how do you fix it by hand? junior