Autocoder

Java Multithreading Interview Questions

Last updated 2026-11-19

Multithreading questions separate candidates who have only read about threads from those who have debugged them. Interviewers ask for definitions, but the follow-ups are always about behaviour: why does this counter lose updates, why does the loop never stop, how would you make this deadlock-free.

This page covers thread basics, the Java memory model essentials, synchronisation, inter-thread communication and the Java 21 virtual threads. Higher-level tools such as executors and locks are on the concurrency utilities page.

Java version17 and later, virtual threads from 21
Key ideasVisibility, atomicity, ordering
Level1 to 5 years of experience

Three problems every concurrency bug comes from

Java Multithreading Interview Questions: questions with worked answers

  1. 1

    What are the ways to create a thread, and what is the difference between start() and run()?

    easy

    You can extend Thread, implement Runnable, implement Callable and submit it to an ExecutorService, or on Java 21 start a virtual thread. Implementing Runnable is preferred because it separates the task from the thread and leaves your class free to extend something else. start() asks the JVM to create a new thread of execution that then calls run(). Calling run() directly is an ordinary method call on the current thread, so nothing runs concurrently.

    java
    Thread t = new Thread(() -> System.out.println(Thread.currentThread().getName()));
    t.run();    // prints "main": no new thread
    t.start();  // prints "Thread-0" (or similar)
  2. 2

    What happens if you call start() twice on the same thread?

    easy

    The second call throws IllegalThreadStateException, because a thread that has already been started (even if finished) is never reusable. Create a new Thread object, or better, use a thread pool that reuses worker threads for many tasks.

  3. 3

    Describe the thread states.

    medium

    NEW before start(); RUNNABLE while running or ready to run; BLOCKED waiting to enter a synchronized block held by another thread; WAITING after wait(), join() or LockSupport.park() with no timeout; TIMED_WAITING for sleep, timed wait or timed join; and TERMINATED when run() has finished. Thread.getState() returns these values, which is also how a jstack dump labels threads.

  4. 4

    What does synchronized do, and what is the difference between a synchronized method and a block?

    medium

    It acquires the monitor lock of an object, guaranteeing mutual exclusion and also a happens-before edge so that writes made inside are visible to the next thread that acquires the same lock. A synchronized instance method locks this, a static synchronized method locks the Class object, and a block locks whatever object you name. Prefer small blocks over private lock objects to narrow the critical section and avoid exposing your lock. Locks are reentrant: a thread already holding the monitor can enter again.

  5. 5

    Predict the output: two threads each increment a shared counter 1,000 times.

    medium

    The result is usually less than 2,000 and varies between runs, because count++ is three steps (read, add one, write) that interleave. Making the method synchronized or using AtomicInteger.incrementAndGet fixes it. Adding volatile alone does not, since volatile gives visibility but not atomicity.

    java
    static int count = 0;
    public static void main(String[] a) throws Exception {
        Runnable r = () -> { for (int i = 0; i < 1000; i++) count++; };
        Thread t1 = new Thread(r), t2 = new Thread(r);
        t1.start(); t2.start(); t1.join(); t2.join();
        System.out.println(count);   // often 1500 to 2000, not always 2000
    }
    // Fix: AtomicInteger count; count.incrementAndGet() in the loop
  6. 6

    What does volatile guarantee and what does it not?

    medium

    A volatile write is visible to every subsequent read of that variable by any thread, and it prevents the reordering of surrounding accesses across it. It does not make compound actions atomic. It is ideal for a stop flag or for safe publication of an immutable object, and unsuitable for counters. Without volatile, the loop below can spin forever because the JIT may hoist the read of running out of the loop.

    java
    class Worker implements Runnable {
        private volatile boolean running = true;
        public void run() { while (running) { /* work */ } }
        public void stop() { running = false; }
    }
  7. 7

    Explain wait, notify and notifyAll. How do they differ from sleep?

    medium

    wait releases the monitor and suspends the thread until another thread calls notify or notifyAll on the same object; all three must be called while holding that monitor or IllegalMonitorStateException is thrown. sleep keeps any locks it holds and only pauses for a time. Always call wait inside a while loop that rechecks the condition, because of spurious wakeups and because another thread may consume the condition first.

    java
    synchronized (lock) {
        while (queue.isEmpty()) {
            lock.wait();          // releases the lock while waiting
        }
        item = queue.poll();
    }
  8. 8

    What is a deadlock? Give a minimal example and ways to prevent it.

    medium

    Deadlock occurs when threads each hold a lock the other needs and wait forever. It needs mutual exclusion, hold and wait, no preemption and a circular wait. The simplest fix is a global lock ordering so every thread acquires lock A before lock B. Others are tryLock with a timeout, holding fewer locks, or using higher-level structures. jstack reports detected deadlocks.

    java
    Object a = new Object(), b = new Object();
    new Thread(() -> { synchronized (a) { pause(); synchronized (b) { } } }).start();
    new Thread(() -> { synchronized (b) { pause(); synchronized (a) { } } }).start();
    // each holds one lock and waits for the other: deadlock
  9. 9

    What is the difference between a race condition and a data race?

    medium

    A data race is a specific memory-model violation: two threads access the same variable, at least one writes, with no happens-before ordering between them. A race condition is a broader logic bug where the result depends on timing, such as check-then-act (if absent then put). You can have a race condition without a data race, for example two synchronised calls that are individually atomic but not atomic as a pair. Use putIfAbsent or compute on ConcurrentHashMap for the check-then-act case.

  10. 10

    Why does double-checked locking need volatile?

    hard

    Object construction is allocation, constructor run and publishing the reference, and the JIT or CPU may reorder the publish before the constructor completes. Another thread could then see a non-null but half-built instance. Declaring the field volatile forbids that reordering. The initialisation-on-demand holder idiom or a single-element enum avoid the problem entirely.

    java
    class Singleton {
        private static volatile Singleton inst;
        static Singleton get() {
            if (inst == null) {
                synchronized (Singleton.class) {
                    if (inst == null) inst = new Singleton();
                }
            }
            return inst;
        }
    }
  11. 11

    What does join() do and why is it needed in the counter example?

    easy

    t.join() blocks the calling thread until t terminates, and it establishes a happens-before edge so the caller sees everything t wrote. Without it, main might print the counter while the workers are still running.

  12. 12

    What is the Java Memory Model happens-before rule set?

    medium

    Happens-before is the guarantee that one action's effects are visible to another. The main edges: program order within a thread; unlock then later lock of the same monitor; volatile write then later volatile read of the same variable; Thread.start() before any action in the started thread; all actions in a thread before another thread returns from join() on it; and writing a final field in a constructor before publication.

  13. 13

    How do you stop a thread properly?

    medium

    Java has no safe forced stop; Thread.stop was removed in later releases. Use cooperative cancellation: call interrupt() and have the task check Thread.currentThread().isInterrupted() or handle InterruptedException. If you catch InterruptedException and cannot propagate it, restore the flag with Thread.currentThread().interrupt() instead of swallowing it. A volatile boolean flag also works for tasks that do not block.

    java
    Thread t = new Thread(() -> {
        try {
            while (!Thread.currentThread().isInterrupted()) {
                Thread.sleep(100);        // throws when interrupted
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    });
    t.start(); t.interrupt();
  14. 14

    What is ThreadLocal and what is its main pitfall?

    medium

    ThreadLocal gives each thread its own copy of a value, useful for per-request context or non-thread-safe helpers like SimpleDateFormat. The pitfall is leaks in thread pools: pooled threads live long, so a value that is not removed with remove() sticks around and may even leak between requests or retain a classloader. Always call remove() in a finally block.

  15. 15

    What are daemon threads?

    medium

    A daemon thread does not keep the JVM alive: when all non-daemon threads finish, the JVM exits and abruptly stops daemon threads without running their finally blocks. Garbage collection and many pool timers are daemons. Set it with setDaemon(true) before start(). Never use a daemon for work that must complete, such as writing a file.

  16. 16

    What are virtual threads (Java 21) and when should you use them?

    hard

    Virtual threads are lightweight threads scheduled by the JVM onto a small pool of carrier platform threads. When one blocks on I/O or a lock from java.util.concurrent, it is unmounted and the carrier runs another, so you can have hundreds of thousands of them. They suit blocking, request-per-thread server code. They do not speed up CPU-bound work, should not be pooled, and a synchronized block that blocks could pin the carrier on Java 21.

    java
    try (var ex = java.util.concurrent.Executors.newVirtualThreadPerTaskExecutor()) {
        for (int i = 0; i < 10_000; i++) {
            ex.submit(() -> { Thread.sleep(1000); return 1; });
        }
    }   // closes and waits for all tasks
  17. 17

    Producer-consumer: implement it simply with a BlockingQueue.

    medium

    A BlockingQueue handles the waiting and notification, so you write no wait or notify. put blocks when a bounded queue is full and take blocks when it is empty. A poison pill value signals the consumer to finish.

    java
    BlockingQueue<Integer> q = new ArrayBlockingQueue<>(5);
    Thread producer = new Thread(() -> {
        try { for (int i = 1; i <= 3; i++) q.put(i); q.put(-1); }
        catch (InterruptedException e) { Thread.currentThread().interrupt(); }
    });
    Thread consumer = new Thread(() -> {
        try { int v; while ((v = q.take()) != -1) System.out.println("got " + v); }
        catch (InterruptedException e) { Thread.currentThread().interrupt(); }
    });
    producer.start(); consumer.start();

Frequently asked questions

Is multithreading asked for freshers?

Basics are: creating threads, start versus run, synchronized and the thread life cycle. Deadlock, volatile and wait/notify appear for candidates with some experience.

What is the difference between a process and a thread?

A process has its own address space; threads of one process share the heap and differ only in stack and registers. See operating systems questions.

Should I use synchronized or ReentrantLock?

synchronized is simpler and fine for most code. ReentrantLock adds tryLock, timed and interruptible acquisition and multiple conditions.

Is volatile enough for a counter?

No. Use AtomicInteger, LongAdder or a lock, since volatile does not make increments atomic.

Related guides

More in Programming Language Interview Questions by Language

See all in this section