Multithreading and concurrency interview questions with Java and Python

Multithreading interview questions check whether you can write code that stays correct when several threads touch the same data: spotting race conditions, choosing between locks, atomics and concurrent collections, avoiding deadlock, and explaining memory visibility. Most rounds mix definitions with a small coding task such as a producer-consumer queue, and many ask when threads are the wrong tool compared with async I/O or separate processes. Java and Python are the most common languages for these questions.

By Published 12 min read

How concurrency questions show up in interviews

Backend and Java loops treat concurrency as a core topic: expect questions on synchronized, the java.util.concurrent package and thread pools, followed by a coding task where you make a class thread safe. Python interviews focus on the GIL and on choosing among threading, multiprocessing and asyncio. Senior rounds turn into debugging stories: a service that hangs under load, a counter that drifts, a thread pool that grows until memory runs out. Interviewers listen for precise vocabulary (atomicity, visibility, ordering) and for a habit of reasoning about every interleaving rather than hoping the timing works out.

Fundamentals

Core concepts interviewers ask about first
QuestionWhat it testsWhat a strong answer shows
What is the difference between a thread and a process?BasicsThreads in one process share the heap and open files, so they communicate cheaply and corrupt each other easily. Processes have separate address spaces and talk through pipes, sockets or shared memory set up on purpose.
Concurrency versus parallelism?VocabularyConcurrency is structuring work as tasks that can make progress independently; parallelism is actually running them at the same instant on several cores. A single core can be concurrent but not parallel.
What is a race condition?Core ideaA result that depends on the timing of threads. The classic forms are read-modify-write (count++) and check-then-act (if the key is missing, insert it).
What is a critical section?Core ideaCode that touches shared mutable state and must not be run by two threads at once. Keep it as short as possible.
Why is count++ not thread safe?AtomicityIt is a read, an add and a write. Two threads can read the same value and both write value plus one, losing an update.
What does thread safe actually mean?PrecisionThe class behaves correctly under any interleaving of calls from many threads, with no extra locking by the caller. Say which operations are safe; compound actions often still need the caller's lock.
What are the states of a Java thread?Java specificsNEW, RUNNABLE, BLOCKED (waiting for a monitor), WAITING, TIMED_WAITING and TERMINATED.
How do you stop a thread cleanly?CooperationAsk it to stop: interrupt it or set a flag it checks, and let it finish its current step. Thread.stop is deprecated because it can leave objects half updated.
Core concepts interviewers ask about first. Scroll sideways on a small screen.
import java.util.concurrent.atomic.AtomicInteger;

public class CounterRace {
    static int unsafeCount = 0;
    static int lockedCount = 0;
    static final Object lock = new Object();
    static final AtomicInteger atomicCount = new AtomicInteger();

    public static void main(String[] args) throws InterruptedException {
        Runnable work = () -> {
            for (int i = 0; i < 100_000; i++) {
                unsafeCount++;                       // read, add, write: not atomic
                atomicCount.incrementAndGet();       // one atomic step
                synchronized (lock) { lockedCount++; } // mutual exclusion
            }
        };
        Thread a = new Thread(work), b = new Thread(work);
        a.start(); b.start();
        a.join(); b.join();
        System.out.println("unsafe=" + unsafeCount + " atomic=" + atomicCount.get() + " locked=" + lockedCount);
    }
}
A lost-update race and two fixes. The unsafe total varies from run to run and is usually below 200000; the atomic and locked totals are always exact.

Memory visibility and the Java memory model

  • What does `volatile` guarantee in Java? A write to a volatile field is visible to every later read of it, and it stops the compiler and CPU from reordering ordinary reads and writes across it in ways that break that. It does not make x++ atomic.
  • What is a happens-before relationship? The rule that decides when one thread's writes are guaranteed visible to another. Unlocking a monitor happens before the next lock of the same monitor; a volatile write happens before later reads; Thread.start and Thread.join create edges too.
  • Why can a thread loop forever on a plain boolean flag? Without volatile or a lock, the JIT may hoist the read out of the loop, and the reading thread never sees the other thread's write. Making the flag volatile fixes it.
  • Why does double-checked locking need `volatile`? Without it, another thread can see the reference to the singleton before the constructor's writes are visible, and use a half-built object.
  • What is false sharing? Two threads writing different variables that sit on the same CPU cache line, so the line bounces between cores. It shows up as poor scaling, and padding or per-thread counters (like Java's LongAdder) remove it.
  • Is `ConcurrentHashMap` enough to make check-then-act safe? Only if you use its atomic methods such as putIfAbsent, computeIfAbsent and merge. A separate containsKey followed by put is still a race.

Locks, conditions and coordination

Which tool to reach for
QuestionWhat it testsWhat a strong answer shows
synchronized or ReentrantLock?Java API judgmentsynchronized is simpler and released automatically. ReentrantLock adds tryLock with a timeout, interruptible waiting, optional fairness and several conditions per lock, at the cost of a mandatory finally unlock.
What is a reentrant lock?DefinitionsThe thread holding it can acquire it again without deadlocking itself, with a hold count that must reach zero before others get it. Both Java options are reentrant; Python's threading.Lock is not, RLock is.
When is a read-write lock worth it?Trade-offsMany readers, rare writers and reads that take a while. For short reads its bookkeeping can make it slower than a plain lock.
wait/notify or a Condition?CoordinationBoth wait inside a lock for a state change. Always wait in a while loop that rechecks the condition, because of spurious wakeups and other threads winning the race.
What do CountDownLatch, CyclicBarrier and Semaphore do?Library knowledgeA latch lets threads wait until a count reaches zero, once. A barrier makes a fixed group wait for each other and can be reused. A semaphore limits how many threads use a resource at once.
How would you make a lazily created singleton thread safe?PatternsThe holder-class idiom or an enum in Java; double-checked locking with volatile if asked to write it by hand.
What is lock-free code?Senior depthProgress without blocking, built on compare-and-swap loops. Mention the ABA problem and that lock-free is harder to get right than a lock.
Which tool to reach for. Scroll sideways on a small screen.
import java.util.ArrayDeque;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class BoundedBuffer<T> {
    private final ArrayDeque<T> items = new ArrayDeque<>();
    private final int capacity;
    private final ReentrantLock lock = new ReentrantLock();
    private final Condition notFull = lock.newCondition();
    private final Condition notEmpty = lock.newCondition();

    public BoundedBuffer(int capacity) { this.capacity = capacity; }

    public void put(T item) throws InterruptedException {
        lock.lock();
        try {
            while (items.size() == capacity) notFull.await();   // loop, not if
            items.addLast(item);
            notEmpty.signal();
        } finally {
            lock.unlock();
        }
    }

    public T take() throws InterruptedException {
        lock.lock();
        try {
            while (items.isEmpty()) notEmpty.await();
            T item = items.removeFirst();
            notFull.signal();
            return item;
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        BoundedBuffer<Integer> buf = new BoundedBuffer<>(2);
        Thread producer = new Thread(() -> {
            try { for (int i = 1; i <= 5; i++) buf.put(i); buf.put(-1); }
            catch (InterruptedException e) { Thread.currentThread().interrupt(); }
        });
        producer.start();
        int sum = 0;
        for (int v = buf.take(); v != -1; v = buf.take()) sum += v;
        producer.join();
        System.out.println("sum=" + sum);   // sum=15
    }
}
A bounded blocking queue with one lock and two conditions, the most common "write it yourself" concurrency task. Producers wait while it is full; consumers wait while it is empty.

Deadlock, livelock and starvation in your code

  • Show a deadlock in ten lines. Thread one locks A then B; thread two locks B then A. If each gets its first lock, both wait forever. Interviewers want you to produce this quickly and then fix it.
  • How do you prevent it? Acquire locks in one global order (for example by account id), hold as few locks as possible, never call unknown code (callbacks, listeners) while holding a lock, or use tryLock with a timeout and back off.
  • How do you find a deadlock in a running Java service? Take a thread dump with jstack or jcmd <pid> Thread.print. The JVM reports monitor deadlocks it detects, and the stack traces show which lock each thread holds and waits for.
  • What is livelock? Threads keep reacting to each other and retrying, so they are busy but make no progress, like two people stepping aside in the same direction. Random backoff usually breaks it.
  • What is starvation? A thread never gets the lock or CPU time it needs because others keep winning. Fair locks and bounded queues reduce it at some throughput cost.
  • Can you deadlock with only one lock? Yes, with a non-reentrant lock taken twice by the same thread, or by waiting for a pool task that cannot run because the pool's threads are all blocked waiting too.
public class OrderedTransfer {
    static final class Account {
        final int id; long balance;
        Account(int id, long balance) { this.id = id; this.balance = balance; }
    }

    static void transfer(Account from, Account to, long amount) {
        Account first = from.id < to.id ? from : to;    // one global order
        Account second = first == from ? to : from;
        synchronized (first) {
            synchronized (second) {
                if (from.balance >= amount) {
                    from.balance -= amount;
                    to.balance += amount;
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Account a = new Account(1, 1_000), b = new Account(2, 1_000);
        Thread t1 = new Thread(() -> { for (int i = 0; i < 50_000; i++) transfer(a, b, 1); });
        Thread t2 = new Thread(() -> { for (int i = 0; i < 50_000; i++) transfer(b, a, 1); });
        t1.start(); t2.start();
        t1.join(); t2.join();
        System.out.println("total=" + (a.balance + b.balance));   // total=2000
    }
}
Avoiding the transfer deadlock by always locking the lower account id first. Thousands of opposite-direction transfers finish and the total is conserved.

Thread pools and executors

  • Why use a thread pool instead of new threads? Creating platform threads is expensive and each one reserves stack memory. A pool reuses threads and, more importantly, caps how many run at once.
  • How many threads should a pool have? Close to the number of cores for CPU-bound work. For I/O-bound work more, roughly cores times (1 + wait time / compute time), then measure. Unbounded is never the answer.
  • What happens when the queue is full? In Java's ThreadPoolExecutor the rejection policy decides: throw, run the task on the caller's thread (natural backpressure), or drop. Be ready to say which you would pick and why.
  • Why are `Executors.newFixedThreadPool` and `newCachedThreadPool` risky defaults? The fixed pool uses an unbounded queue, so a slow downstream lets tasks pile up in memory. The cached pool can create threads without limit.
  • What is a `CompletableFuture` for? Composing async steps (thenApply, thenCompose, allOf) without blocking a thread per step. Mention which executor runs each stage; by default the async variants use the common fork-join pool.
  • What are virtual threads? Lightweight threads managed by the JVM (final in Java 21) that unmount from their carrier thread while blocked on I/O, so blocking-style code can handle very many concurrent requests. They help I/O-bound work, not CPU-bound work, and should not be pooled.
  • Why are `ThreadLocal` values dangerous in a pool? Pool threads live forever, so a value set for one request leaks into the next unless it is removed in a finally block.
import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class VirtualThreadsDemo {
    public static void main(String[] args) {
        AtomicInteger done = new AtomicInteger();
        long start = System.nanoTime();
        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
            for (int i = 0; i < 10_000; i++) {
                executor.submit(() -> {
                    Thread.sleep(Duration.ofMillis(100));   // blocking call: the virtual thread unmounts
                    done.incrementAndGet();
                    return null;
                });
            }
        }   // close() waits for every task
        long ms = (System.nanoTime() - start) / 1_000_000;
        System.out.println("done=" + done.get() + " under 5 s: " + (ms < 5_000));
    }
}
Ten thousand blocking tasks on virtual threads (Java 21+). Each sleeps 100 ms. Run one after another that would take about 1,000 seconds; with one virtual thread per task the waits overlap and the whole run takes a small fraction of that.

Python: the GIL, threads, processes and asyncio

Python concurrency questions
QuestionWhat it testsWhat a strong answer shows
What is the GIL?CPython internalsThe global interpreter lock lets only one thread execute Python bytecode at a time in a standard CPython build. Threads still overlap while waiting on I/O, because blocking calls release the lock.
Does the GIL make my code thread safe?Common mythNo. x += 1 is several bytecode steps and is not guaranteed to be atomic. Whether updates are actually lost depends on the interpreter version and build (the free-threaded build makes it far more likely), so shared counters still need a Lock.
Threads, processes or asyncio for 500 HTTP calls?Choosing a modelI/O-bound, so threads or asyncio. asyncio scales to more connections with less memory but needs async libraries all the way down.
And for resizing 10,000 images?Choosing a modelCPU-bound, so multiprocessing or ProcessPoolExecutor, one worker per core, accepting the cost of pickling data between processes.
What happens if you call a blocking function inside a coroutine?asyncio pitfallsIt blocks the whole event loop and every other task. Use the async version or asyncio.to_thread.
Is there a CPython without the GIL?Current awarenessYes: an optional free-threaded build arrived as experimental in Python 3.13 and became officially supported, still optional, in 3.14. Most installs still use the default build, and C extensions must declare support.
Python concurrency questions. Scroll sideways on a small screen.
import threading
from concurrent.futures import ThreadPoolExecutor

counter = 0
lock = threading.Lock()


def add_many(n):
    global counter
    for _ in range(n):
        with lock:            # += alone is not guaranteed atomic
            counter += 1


with ThreadPoolExecutor(max_workers=4) as pool:
    for _ in range(4):
        pool.submit(add_many, 100_000)

print(counter)  # 400000
Threads share memory, so a shared counter needs a lock even under the GIL: the language does not promise that `+=` is atomic. The pool also shows the standard way to run blocking calls concurrently.
import asyncio
import time


async def fetch(name, delay):
    await asyncio.sleep(delay)      # stands in for a network call
    return f"{name} done"


async def main():
    start = time.perf_counter()
    results = await asyncio.gather(fetch("a", 1), fetch("b", 1), fetch("c", 1))
    print(results, round(time.perf_counter() - start))


asyncio.run(main())  # ['a done', 'b done', 'c done'] 1
asyncio runs many waits on one thread. Three one-second waits finish in about one second because they overlap.

Senior and scenario questions

  • A service hangs under load but CPU is near zero. What do you check? Threads are waiting, not working: take thread dumps a few seconds apart and look for threads stuck on the same lock, a pool fully blocked on a slow dependency, or a connection pool that is empty.
  • Latency climbs when you add threads. Why? Lock contention, context switching, or a shared downstream (database, disk) that is already saturated. More threads only help while something is idle.
  • Design a thread-safe in-memory cache with expiry. ConcurrentHashMap with computeIfAbsent so only one thread loads a missing key, entries that carry an expiry time, and a scheduled cleanup or lazy eviction on read.
  • How do you test concurrent code? Stress tests with many threads and repeated runs, latches to force specific interleavings, tools such as jcstress for the Java memory model, and code review that names the lock guarding each field.
  • When would you avoid shared state entirely? When message passing fits: a single owner thread per piece of state fed by a queue, or an actor model. Fewer locks, easier reasoning, at the cost of a queue hop.

Fictional example

Answering "Our daily totals are sometimes slightly low. What could cause that?"
Interviewer
A Java service counts events in a shared HashMap of counters. Totals are occasionally a little lower than the logs say. Where would you look?
Candidate
Low totals point to lost updates. I would look for a read-modify-write on shared state with no coordination, and a plain HashMap updated by several request threads is the first suspect: two threads can read the same count and both write count plus one, and concurrent puts can even corrupt the map's internal structure. My fix would be a ConcurrentHashMap whose values are LongAdder, updated with computeIfAbsent and then increment, so each step is atomic and the hot counters do not contend on one cache line. To confirm the cause before shipping, I would write a stress test with sixteen threads doing a million increments each against the old code and show the total comes out short, then run the same test on the fix.

How to prepare for concurrency questions

  1. Learn the vocabulary preciselyAtomicity, visibility, ordering, race condition, critical section, deadlock, livelock, starvation. Vague answers are the most common way to lose these questions.
  2. Write the classic tasks by handA bounded blocking queue, a thread-safe lazy singleton, two threads printing odd and even numbers in turn, and a deadlock plus its fix. Run each one many times.
  3. Read your language's concurrency libraryFor Java: java.util.concurrent, ExecutorService, CompletableFuture, the atomics and virtual threads. For Python: threading, concurrent.futures, multiprocessing and asyncio.
  4. Practice explaining interleavingsFor any shared variable, narrate a bad schedule step by step: thread one reads, thread two reads, both write. Interviewers reward that more than naming a fix.
  5. Prepare one real storyA race, deadlock or pool exhaustion you debugged: the symptom, how you proved the cause, the fix and how you tested it.

Concurrency sits between two other topics. Operating system interview questions covers what the kernel does underneath (scheduling, context switches and semaphores), and DBMS interview questions covers how databases handle the same problems with transactions and isolation. For Java services, Spring Boot interview questions shows where request threads, pools and @Async meet a real framework, and backend developer interview questions places all of this in a full loop.

Concurrency answers are easy to get half right out loud, so rehearse them. Natively, an AI interview assistant on Mac and Windows, transcribes a mock round as you explain an interleaving, can suggest an answer or fix code it reads from a screenshot of the task, and keeps the transcript and notes so you can spot where your explanation went vague. On Pro or the free trial it can draw on your résumé and the job description you add.

Questions people ask

What are the most common multithreading interview questions?

Thread versus process, race conditions, synchronized versus ReentrantLock, volatile and visibility, deadlock and how to avoid it, thread pool sizing, and a coding task such as a producer-consumer queue.

What is the difference between concurrency and parallelism?

Concurrency is structuring a program as tasks that can make progress independently. Parallelism is running tasks at the same instant on several cores. One core can be concurrent but not parallel.

How do you prevent deadlock in code?

Acquire locks in one consistent global order, hold as few locks as possible, never call unknown code while holding a lock, or use tryLock with a timeout and back off.

Does Python support real multithreading?

Python threads are real OS threads, but in the standard CPython build the GIL lets only one run Python bytecode at a time. Threads work well for I/O-bound work; CPU-bound work usually goes to processes.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP