Java Multithreading Interview Questions and Answers (Java 21)
-
Last Updated:
-
By: Suraj S R
-
Series

Java multithreading interview questions (Java 21): thread lifecycle, volatile vs synchronized, wait vs sleep, deadlocks and virtual threads — 23 Q&A.
If you are getting ready for a Java interview, these Java multithreading interview questions will cover almost everything you get asked about threads. I have sat on both sides of the table in banking and payments for close to ten years. So I have arranged these questions the way interviews actually flow: easy warm-up questions first, then the tricky ones that senior roles care about.
Threads feel scary at the start. But the core ideas are simple once you see them clearly. In this guide, I explain each answer in plain words, add clear runnable code, and tell you the follow-up the interviewer usually asks next. I have also added Java 21 virtual threads, which many older articles skip.
Why does this topic matter so much in interviews? Modern servers have many CPU cores. A single thread uses only one core at a time. With several threads, your program uses many cores together and finishes the work faster. That raw speed is why almost every backend role tests threads.
If you are new to interview prep, start with the Core Java interview questions for freshers guide, then come back here for threads. Read the answers out loud. That is the best way to sound calm and clear in the room. Let us start with the basics.
These first questions check whether you know the building blocks. Keep each answer crisp and confident. An interviewer uses them to decide how deep to go next.
Answer – A process is a program that is running. The operating system gives it its own separate memory space. A thread is a smaller unit of work that runs inside a process. One process can hold many threads, and all of them share that same memory.
Here is the mental picture I use. A process is a house with its own address. Threads are the people living inside that one house. They share the kitchen, the fridge, and the furniture. Because they share everything, they talk to each other very fast. But that same sharing is exactly why we need careful coordination later.
Let me go one level deeper, since interviewers love this follow-up. Inside a process, every thread gets its own stack and its own program counter. Yet all threads share the same heap, where your objects live. So two threads can see and change the same object. That shared heap is the root of almost every concurrency bug.
There is also a cost angle worth mentioning. Switching the CPU between two processes is expensive, because the OS must swap out a lot of state. Switching between two threads of the same process is much cheaper. That is one big reason we reach for multithreading when we want more work done at once.
public class Shared {
static int counter = 0; // lives on the shared heap
public static void main(String[] args) throws InterruptedException {
Runnable job = () -> {
for (int i = 0; i < 1000; i++) counter++; // both threads touch it
};
Thread t1 = new Thread(job);
Thread t2 = new Thread(job);
t1.start(); t2.start();
t1.join(); t2.join();
System.out.println(counter); // often < 2000, because of a race
}
}Answer – There are two classic ways, plus one modern way I always mention to score extra points.
I prefer the Runnable way, and so do most interviewers:
The modern way is to use an ExecutorService with a thread pool, or Java 21 virtual threads. In real projects, we almost never create raw threads by hand. We hand tasks to a pool instead, and the pool manages the threads for us.
Notice the small detail in the code below. Both ways end with start(), never run(). That one habit saves you from the most common beginner mistake.
// Way 1: extend Thread
class Downloader extends Thread {
public void run() { System.out.println("downloading on " + getName()); }
}
// Way 2 (preferred): implement Runnable
class Report implements Runnable {
public void run() { System.out.println("report done"); }
}
public class Demo {
public static void main(String[] args) {
new Downloader().start(); // way 1
new Thread(new Report()).start(); // way 2
new Thread(() -> System.out.println("lambda task")).start(); // way 2 with lambda
}
}| Interview insight: when they ask “which way is better and why”, say Runnable, and give two reasons: single inheritance stays free, and the task is decoupled from the thread. That shows design sense, not just syntax. |
Answer – Both describe a task you want to run on a thread. The real difference is what they give back.
Runnable has a run() method. It returns nothing, and it cannot throw a checked exception. Callable has a call() method. It returns a value, and it can throw a checked exception. So when you need a result from your background work, you pick Callable.
You run a Callable through an ExecutorService. In return, you get a Future object. You then call future.get() to collect the result once it is ready. One important point: future.get() blocks. It waits until the task finishes, so call it only when you truly need the answer.
There is one more small point worth saying. Runnable has existed since Java 1.0. Callable arrived later, with the concurrency library in Java 5. So Callable is simply the newer and richer choice. In the code below, watch how call() returns a value and how get() picks it up.
import java.util.concurrent.*;
public class CallableDemo {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(1);
Callable<Integer> job = () -> {
Thread.sleep(500); // pretend this is slow work
return 2 + 3; // returns a value
};
Future<Integer> future = pool.submit(job);
System.out.println("doing other work...");
System.out.println("result = " + future.get()); // blocks, prints 5
pool.shutdown();
}
}Answer – A Java thread moves through six states. These come straight from the Thread.State enum, so it is good to name them exactly.

One point is worth stressing. RUNNABLE in Java covers both ready and actually running. The JVM does not split those into two states. Instead, the operating system scheduler decides which ready thread gets the CPU right now.
You can watch these states in code with getState(). This is a great thing to demo in an interview, because it proves you understand the model and not just the words. The diagram above shows the same transitions as a map.
public class StateDemo {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
try { Thread.sleep(300); } catch (InterruptedException e) { }
});
System.out.println(t.getState()); // NEW
t.start();
System.out.println(t.getState()); // RUNNABLE
Thread.sleep(100);
System.out.println(t.getState()); // TIMED_WAITING (it is sleeping)
t.join();
System.out.println(t.getState()); // TERMINATED
}
}Answer – This is a classic trap, so answer it slowly. Calling start() creates a brand new thread and then runs your code on that new thread. Calling run() directly starts nothing new. It simply runs the method on the current thread, just like a normal method call.
So if you call run() yourself, there is no real multithreading at all. Everything happens on one thread, one after another. I have seen candidates lose easy points here, so say start() for a new thread every time.
Why does Java even let you call run() directly? Because the Thread class implements Runnable. So run() is just a normal public method on the object. Nothing stops you from calling it, and that is exactly why the trap works.
The code below makes the difference visible. Watch the thread name that gets printed. With run(), it prints the caller’s name. With start(), it prints a fresh thread name.
public class StartVsRun {
public static void main(String[] args) {
Runnable task = () -> System.out.println("running on " + Thread.currentThread().getName());
new Thread(task).run(); // prints "running on main" -> no new thread
new Thread(task).start(); // prints "running on Thread-1" -> real new thread
}
}Answer – A user thread keeps the JVM alive. The JVM waits for every user thread to finish before it shuts down. A daemon thread is a background helper, and the JVM does not wait for it. When all user threads end, any daemon threads are stopped too, even in the middle of their work.
Garbage collection is the famous example. It runs on a daemon thread. Other good fits are background log flushers, metrics senders, and cache cleaners. These jobs should never hold the whole application open on their own.
There is one rule you must remember. You set a thread as daemon with setDaemon(true), and you must do it before you call start(). If you try after the thread has started, Java throws IllegalThreadStateException.
The code shows the key effect. The main method ends quickly, so the daemon never gets to print its later message. A user thread, by contrast, would have kept the program running.
public class DaemonDemo {
public static void main(String[] args) throws InterruptedException {
Thread helper = new Thread(() -> {
try {
Thread.sleep(2000);
System.out.println("daemon woke up"); // never prints
} catch (InterruptedException e) { }
});
helper.setDaemon(true); // must be set before start()
helper.start();
System.out.println("main is done"); // JVM exits right after this
}
}Answer – join() makes one thread wait for another to finish. Say your main thread needs a result from a worker. If main calls worker.join(), then main pauses right there until the worker is done.
So join() is how you wait for background work before you move on. Without it, your main thread may race ahead and read a result that is not ready yet. That timing bug is easy to create and hard to spot.
You can also pass a timeout, like join(2000), to wait at most two seconds. After that, the caller continues no matter what. This guard is useful when a worker might hang and you do not want to wait forever.
In the example, main starts two workers and then joins both. Only after both finish does main print the total. Remove the joins, and the total may print as zero.
public class JoinDemo {
static int a, b;
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> a = slowAdd(2, 3));
Thread t2 = new Thread(() -> b = slowAdd(5, 5));
t1.start(); t2.start();
t1.join(); // wait for t1
t2.join(); // wait for t2
System.out.println("total = " + (a + b)); // 15, only after both finish
}
static int slowAdd(int x, int y) {
try { Thread.sleep(200); } catch (InterruptedException e) { }
return x + y;
}
}Answer – No, you cannot. A thread runs only once. Once it reaches the TERMINATED state, it is finished for good. If you call start() on it a second time, Java throws IllegalThreadStateException.
The reason is simple. A Thread object tracks its own state inside. After it finishes, that state cannot go back to NEW. So the second start() has nowhere valid to go, and it fails fast.
So what do you do when you need to run the task again? You create a new Thread, or better, you submit the task to a thread pool. A pool reuses its own threads under the hood, but your task can be submitted as many times as you like. That is the clean, production-grade pattern.
public class StartTwice {
public static void main(String[] args) {
Thread t = new Thread(() -> System.out.println("hi"));
t.start();
t.start(); // throws IllegalThreadStateException
// Correct pattern: reuse a pool, resubmit the task
var pool = java.util.concurrent.Executors.newFixedThreadPool(2);
Runnable task = () -> System.out.println("safe run");
pool.submit(task);
pool.submit(task); // fine: same task, pooled threads
pool.shutdown();
}
}Now the questions get sharper. Here the interviewer checks if you can keep shared data safe. Focus on three themes: visibility, locking, and coordination between threads.
Answer – Both use a lock, called a monitor, so that only one thread can run the protected code at a time. The difference is how much code you lock and which object you lock on.
A synchronized method locks on the whole object (this) for instance methods, or on the class object for static methods. A synchronized block locks only the lines inside the braces, and you choose the object to lock on. So blocks give you much finer control.
I prefer blocks in real code, and here is why. They keep the locked region small. A smaller region means threads wait less, and your app stays faster under load. Lock only the few lines that touch shared state, not the entire method with its slow I/O and logging.
Static synchronized is worth a quick mention too. It locks on the Class object, not on any single instance. So two different objects of the same class still block each other for static synchronized methods. The code below shows all three forms side by side.
public class Counter {
private int count = 0;
private final Object lock = new Object();
// locks the whole method on this
public synchronized void addMethod() { count++; }
// locks only the critical line, on a private lock object
public void addBlock() {
doSlowLogging(); // not locked - good
synchronized (lock) { count++; } // only this is locked
}
// locks on the Counter.class object (shared by all instances)
public static synchronized void staticWork() { /* ... */ }
private void doSlowLogging() { }
}Answer – volatile makes a variable’s latest value visible to every thread. Without it, one thread may keep reading a stale copy from its own CPU cache. So volatile guarantees visibility, and it also stops some risky instruction reordering around that variable.
But here is the catch that interviewers wait for. volatile does not make compound actions atomic. Take count++. That looks like one step, but it is really three: read the value, add one, write it back. Two threads can slip between those steps and lose an update. So volatile alone cannot keep a counter correct.
When should you use it then? Use volatile for a simple flag that one thread sets and other threads read. A classic case is a ‘running’ flag that signals a background loop to stop. One writer, many readers, single value: that is the sweet spot.
The code shows the good use and the bad use together. A stop flag is perfect for volatile. But the hit counter is not, because ++ is not atomic.
public class VolatileDemo {
private volatile boolean running = true; // GOOD use: a simple flag
private volatile int hits = 0; // BAD use: ++ is not atomic
public void stop() { running = false; } // every thread sees this at once
public void loop() {
while (running) { // reads the fresh value each time
hits++; // still unsafe: read-modify-write can be lost
}
}
}| Interview insight: the follow-up is always “so can I use volatile for a counter?” Answer no, and explain the read-modify-write problem in three steps. That is the exact point they are testing. |
Answer – volatile works on a single variable and gives only visibility. synchronized works on a block of code and gives both visibility and mutual exclusion, which means atomicity.
There is also a cost difference. volatile never blocks a thread, so it is very lightweight. synchronized can make a thread wait for the lock, so it costs more when many threads fight over it. Because of that gap, you pick the tool based on the job.
A quick example makes the choice clear. A boolean ‘stop’ flag that one thread sets and others read fits volatile perfectly. But a bank balance that you read, check, and then update needs synchronized, because those three steps must stay together as one unit.
The code below puts them next to each other. Here the flag uses volatile and stays lock-free. Meanwhile the balance uses synchronized, so the whole read-check-write runs as one safe step.
public class Account {
private volatile boolean frozen = false; // visibility only - fine for a flag
private int balance = 1000;
public void freeze() { frozen = true; } // readers see it immediately
// atomic: the read, the check, and the write stay together
public synchronized void withdraw(int amount) {
if (!frozen && balance >= amount) {
balance -= amount;
}
}
}Answer – A race condition happens when two threads touch the same data at the same time, and the final result depends on timing. The classic case is two threads running count++ together. Some updates simply get lost, so the final count is too low.
Why does it happen? Because count++ is not one action. It is a read, then an add, then a write. If both threads read the same old value first, they both write back the same new value, and one increment vanishes. The bug is also hard to catch, since it may pass on your laptop and fail in production under load.
You prevent it by making the shared update safe. Three common tools do the job. First, wrap the update in a synchronized block. Second, use an explicit Lock. Third, reach for an atomic class like AtomicInteger. Each one makes sure only one thread changes the value at a time.
The code shows the broken version and two clean fixes. Run the broken one in a loop, and you will see numbers below 2000. The fixed ones always give exactly 2000.
import java.util.concurrent.atomic.AtomicInteger;
public class RaceDemo {
int bad = 0; // unsafe
int good = 0; // guarded by synchronized
AtomicInteger best = new AtomicInteger(0);
void unsafe() { bad++; } // race condition: updates get lost
synchronized void safe() { good++; } // one thread at a time
void atomic() { best.incrementAndGet(); } // lock-free and safe
}Answer – Both pause a thread, yet they are very different animals. This pair is one of the most asked Java multithreading interview questions, so be precise.
sleep()
wait()
So the one-line summary is this: sleep() holds the lock, wait() releases it. That single sentence answers the question cleanly and shows you know the deeper difference.
One more detail helps you in the room. sleep() is a static method, so it always pauses the current thread. wait() is an instance method you call on a shared lock object, so it ties directly to that object’s monitor. The code makes both behaviours clear.
public class WaitVsSleep {
private final Object lock = new Object();
void withSleep() throws InterruptedException {
synchronized (lock) {
Thread.sleep(1000); // still holds the lock while sleeping
}
}
void withWait() throws InterruptedException {
synchronized (lock) {
lock.wait(); // releases the lock, waits for notify()
}
}
}Answer – These three methods let threads coordinate with each other. wait() parks the current thread and releases the lock. notify() wakes up one waiting thread. notifyAll() wakes up all of them, and then they compete for the lock again.
Now, why must they sit inside synchronized code? Because each of these methods needs you to hold the object’s monitor lock first. If you call them without the lock, Java throws IllegalMonitorStateException. So you always use them inside a synchronized block or method.
In practice, I prefer notifyAll() over notify() for safety. With plain notify(), you might wake the wrong single thread and leave the right one asleep, which can stall the whole app. notifyAll() wakes everyone, and only the correct thread proceeds.
There is one more rule that catches people out. Always wait inside a while loop, never an if. A thread can wake up without a matching notify, which is called a spurious wake-up. The while loop re-checks the condition and sends the thread back to wait if it is not truly ready. The producer-consumer snippet below shows the full pattern.
public class Buffer {
private final Object lock = new Object();
private boolean ready = false;
public void consume() throws InterruptedException {
synchronized (lock) {
while (!ready) { // while, not if (guards spurious wake-ups)
lock.wait(); // releases lock, parks thread
}
System.out.println("consumed");
ready = false;
}
}
public void produce() {
synchronized (lock) {
ready = true;
lock.notifyAll(); // wake waiting consumers
}
}
}Answer – A deadlock is when two or more threads wait for each other forever, and nobody moves. Picture it simply. Thread A holds lock 1 and wants lock 2. Thread B holds lock 2 and wants lock 1. Both wait, and both are stuck.
Four conditions must all be true for a deadlock to form: mutual exclusion, hold and wait, no preemption, and circular wait. If you break even one of them, a deadlock cannot happen. The one that is easiest to break in code is circular wait.
The simplest fix is lock ordering. Make every thread grab locks in the same fixed order. Once the order is the same everywhere, the circle cannot close, and the deadlock is gone.
The code below creates a deadlock on purpose, then shows the fix. In the broken version, each method takes the two locks in opposite order. In the fixed version, both methods take lock1 first, then lock2.
public class DeadlockDemo {
private final Object lock1 = new Object();
private final Object lock2 = new Object();
// DEADLOCK: opposite lock order
void methodA() { synchronized (lock1) { synchronized (lock2) { } } }
void methodB() { synchronized (lock2) { synchronized (lock1) { } } }
// FIX: both methods take lock1 then lock2, always
void safeA() { synchronized (lock1) { synchronized (lock2) { } } }
void safeB() { synchronized (lock1) { synchronized (lock2) { } } }
}| Interview insight: in payments systems I have seen deadlocks from two services locking two accounts in a different order during a transfer. The fix was always the same: lock the lower account id first. A real story like this lands well in interviews. |
Answer – Both are problems where threads fail to make progress, but for different reasons.
Starvation is when a thread rarely gets the CPU or a lock, because other, greedier threads keep winning. The starved thread just waits and waits. A fairness policy on a lock helps here. A fair lock hands itself to the thread that has waited the longest, so nobody is left behind.
Livelock is sneakier. The threads are active and keep changing state, yet no real work gets done. Think of two people in a narrow corridor. Both step aside, both step back, again and again, and neither passes. A short random backoff usually breaks the pattern.
How do you spot these in practice? A starved thread shows a long wait in a thread dump. A livelock shows high CPU usage with no real progress. Both need a design fix, not just a bigger server. The code shows how to build a fair lock to fight starvation.
import java.util.concurrent.locks.ReentrantLock;
public class Fairness {
// true = fair: the longest-waiting thread gets the lock next
private final ReentrantLock lock = new ReentrantLock(true);
public void work() {
lock.lock();
try {
// critical section - no thread is starved under the fair policy
} finally {
lock.unlock();
}
}
}These last questions suit senior, lead, and architect roles. They move from syntax to judgement. So expect follow-ups about real production trouble and modern Java 21 features.
Answer – The Java Memory Model, or JMM, defines when a write by one thread becomes visible to another thread. Without such rules, the compiler and CPU are free to reorder and cache things, and multithreaded code would be a guessing game.
The core idea is the happens-before relationship. If action A happens-before action B, then B is guaranteed to see the effects of A. A few rules give you this guarantee for free:
Here is the practical takeaway for the interview. You rarely reason about the memory model line by line. Instead, you use synchronized, volatile, and the concurrency classes correctly. In return, they hand you the right happens-before links for free.
The code shows a safe publish. The writer sets the data first, then sets a volatile flag. Because the volatile write happens-before the reader’s volatile read, the reader is guaranteed to see the finished data, not a half-built object.
public class SafePublish {
private int data = 0;
private volatile boolean ready = false; // the happens-before gate
public void writer() {
data = 42; // 1: ordinary write
ready = true; // 2: volatile write - publishes everything before it
}
public void reader() {
if (ready) { // volatile read
System.out.println(data); // guaranteed to see 42, never 0
}
}
}Answer – synchronized is simple, but it is also rigid. The Lock classes in java.util.concurrent give you more power and more options.
ReentrantLock adds three things synchronized cannot do:
ReadWriteLock goes further by splitting into a read lock and a write lock:
There is one rule you must never forget. Always release the lock in a finally block. If you skip it, a crash inside the critical section leaves the lock held forever, and every other thread hangs.
The code shows two things. First, tryLock() with a timeout, so a thread can give up instead of waiting forever. Second, a ReadWriteLock, where reads run in parallel and writes stay exclusive.
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.*;
public class LockDemo {
private final ReentrantLock lock = new ReentrantLock();
private final ReadWriteLock rw = new ReentrantReadWriteLock();
public void tryWithTimeout() throws InterruptedException {
if (lock.tryLock(1, TimeUnit.SECONDS)) { // wait at most 1 second
try { /* critical section */ }
finally { lock.unlock(); } // always unlock
} else {
System.out.println("could not get the lock, backing off");
}
}
public void read() {
rw.readLock().lock(); // many readers together
try { /* read shared data */ }
finally { rw.readLock().unlock(); }
}
public void write() {
rw.writeLock().lock(); // exclusive for writers
try { /* update shared data */ }
finally { rw.writeLock().unlock(); }
}
}Answer – Atomic classes like AtomicInteger and AtomicLong let you update a value safely without any lock. So they are fast and they scale well for simple counters.
They work using compare-and-swap, or CAS. The idea is short. CAS says: if the value is still the old value I expect, change it to the new value; otherwise, tell me it failed and I will retry. The CPU does this check-and-set in one single atomic step, so no other thread can slip in between.
Because there is no lock, there is no blocking. Under high contention for a simple update, this often beats synchronized. This lock-free style is the heart of much of the java.util.concurrent library.
One honest caution is worth adding. Under very heavy contention, CAS may retry many times and waste CPU. For a single counter it still shines. But for complex shared state, a plain lock is sometimes simpler and clearer. The code shows the easy incrementAndGet() and a manual CAS loop so you can see the retry idea.
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicDemo {
private final AtomicInteger count = new AtomicInteger(0);
public void simple() {
count.incrementAndGet(); // safe ++ with no lock, uses CAS inside
}
// what CAS looks like by hand: read, compute, try to swap, retry if it failed
public void manualCas() {
int oldValue, newValue;
do {
oldValue = count.get();
newValue = oldValue + 1;
} while (!count.compareAndSet(oldValue, newValue)); // retry on failure
}
}Answer – Creating a new thread for every task is wasteful and risky. A thread pool reuses a small set of threads, which is the professional way to run many tasks.
In most backend services, a fixed ThreadPoolExecutor is the default choice. You size it to your workload, give it a bounded queue, and keep it under control. A bounded queue matters, because an unbounded one can hide a backlog until you run out of memory.
The code shows both. First, a simple fixed pool through the Executors helper. Second, a ThreadPoolExecutor built by hand, so you can see every knob you control in production.
import java.util.concurrent.*;
public class PoolDemo {
public static void main(String[] args) {
// simple fixed pool
ExecutorService pool = Executors.newFixedThreadPool(4);
for (int i = 0; i < 10; i++) pool.submit(() -> doWork());
pool.shutdown();
// full control in production: core, max, keep-alive, bounded queue
ThreadPoolExecutor custom = new ThreadPoolExecutor(
4, 8, 60, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(100), // bounded queue
new ThreadPoolExecutor.CallerRunsPolicy() // back-pressure when full
);
custom.submit(() -> doWork());
custom.shutdown();
}
static void doWork() { }
}Answer – This is a favourite for experienced roles, so I give a step-by-step answer. First, capture a thread dump. You can use jstack, or jcmd, or send a kill -3 to the process. The dump usually prints a clear line: “Found one Java-level deadlock”, and it names the threads and the locks involved.
Next, read the lock cycle. The dump shows which thread holds which lock and what each one is waiting for. Tools like VisualVM or a commercial profiler show the same thing visually, which helps a lot during a live incident.
Then fix the root cause, not the symptom. Enforce one global lock order, so a cycle can never form. Or switch to tryLock() with a timeout, so a blocked thread backs off and retries instead of waiting forever. In banking systems, I pair this with good logging around each lock, so the next incident is faster to solve.
You can also detect deadlocks from inside the JVM. The ThreadMXBean has a findDeadlockedThreads() method. A small watchdog can call it on a timer and raise an alert. The code shows that watchdog check.
import java.lang.management.*;
public class DeadlockWatchdog {
public static void check() {
ThreadMXBean bean = ManagementFactory.getThreadMXBean();
long[] stuck = bean.findDeadlockedThreads(); // null if none
if (stuck != null) {
ThreadInfo[] info = bean.getThreadInfo(stuck);
for (ThreadInfo t : info) {
System.out.println("DEADLOCKED: " + t.getThreadName());
}
}
}
// On the command line during an incident:
// jcmd <pid> Thread.print | jstack <pid>
}Answer – Virtual threads are the headline feature of Java 21, from Project Loom. They change how we scale concurrent code, and most older interview articles miss them, so mentioning them makes you stand out.
A normal thread, now called a platform thread, maps to one operating system thread. OS threads are heavy, so you can realistically run only a few thousand. A virtual thread is managed by the JVM itself and is extremely light. You can run millions of them. When a virtual thread blocks on input or output, the JVM quietly parks it and frees the real OS thread to do other work.
The best part is how it reads. You write plain, simple, blocking code, and it scales like complex asynchronous code. So you get high throughput without callback spaghetti, and your stack traces stay clean and easy to debug.
One caveat is worth stating, because interviewers probe it. Virtual threads shine for I/O-bound work, such as many network or database calls. They do not speed up CPU-bound number crunching, since that still needs real cores. The code shows two ways to launch them.
import java.util.concurrent.*;
public class VirtualThreads {
public static void main(String[] args) throws InterruptedException {
// 1: start a single virtual thread
Thread.ofVirtual().start(() -> System.out.println("hi from a virtual thread"));
// 2: a pool that makes a fresh virtual thread per task
try (var pool = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 1_000_000; i++) { // a million tasks is fine
pool.submit(() -> handleRequest());
}
} // close() waits for all tasks to finish
}
static void handleRequest() { /* blocking I/O here scales well */ }
}| Interview insight: if they ask “when do virtual threads not help?”, say CPU-bound work, and explain why. Virtual threads win by freeing the OS thread during I/O waits. Heavy computation never waits, so there is nothing to free. |
Answer – ThreadLocal gives each thread its own private copy of a variable. Since nothing is shared, you need no synchronization at all. Each thread simply reads and writes its own copy, with zero contention.
Where does this help? It is great for per-request context, like the current user id or a trace id in a web app. It is also the standard fix for classes that are not thread-safe, such as the old SimpleDateFormat. You give each thread its own instance, so the threads never collide.
But there is one trap you must call out, and senior interviewers always look for it. In a thread pool, threads are reused for many tasks. So if you forget to clean up, old data leaks into the next task that runs on that same thread. In a long-lived pool, this can even cause a memory leak.
The fix is simple and important. Always call remove() in a finally block when the task is done. The code shows the safe pattern with a per-thread date formatter.
import java.text.SimpleDateFormat;
import java.util.Date;
public class ThreadLocalDemo {
// one formatter per thread - SimpleDateFormat is not thread-safe
private static final ThreadLocal<SimpleDateFormat> FORMAT =
ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));
public static String today() {
try {
return FORMAT.get().format(new Date());
} finally {
FORMAT.remove(); // crucial inside thread pools to avoid leaks
}
}
}