Skip to lesson

Concurrency interview review

Most Java concurrency interviews come back to a handful of comparisons. A strong answer gives the difference in one sentence, says when to use each, and backs it with a tiny example you could write on a whiteboard.

synchronized versus ReentrantLock, volatile versus atomic

synchronized is the built-in lock: simple, and released automatically when the block ends, even after an exception.

Example 1 · volatile versus AtomicInteger versus synchronized, and tryLock

LockAndAtomicDemo.javaJava
import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicInteger;import java.util.concurrent.locks.ReentrantLock;
public class LockAndAtomicDemo {    static volatile int volatileCount = 0;                 // visible, but ++ is not atomic    static final AtomicInteger atomicCount = new AtomicInteger();    static int syncCount = 0;    static final Object syncLock = new Object();
    // 4 threads each run 'increment' 100,000 times    static void hammer(Runnable increment) throws InterruptedException {        Thread[] threads = new Thread[4];        for (int i = 0; i < threads.length; i++) {            threads[i] = new Thread(() -> {                for (int j = 0; j < 100_000; j++) increment.run();            });            threads[i].start();        }        for (Thread t : threads) t.join();    }
    public static void main(String[] args) throws InterruptedException {        hammer(() -> volatileCount++);        hammer(atomicCount::incrementAndGet);        hammer(() -> { synchronized (syncLock) { syncCount++; } });        System.out.println("volatile int:  " + volatileCount + " (expected 400000)");        System.out.println("AtomicInteger: " + atomicCount.get());        System.out.println("synchronized:  " + syncCount);
        // something synchronized cannot do: give up after a timeout        ReentrantLock counterLock = new ReentrantLock();        Thread holder = new Thread(() -> {            counterLock.lock();            try { Thread.sleep(300); } catch (InterruptedException e) { /* exit */ }            finally { counterLock.unlock(); }        });        holder.start();        Thread.sleep(50);        boolean got = counterLock.tryLock(100, TimeUnit.MILLISECONDS);        System.out.println("tryLock for 100 ms while another thread holds it: " + got);        holder.join();    }}
Sample output
volatile int:  328036 (expected 400000)
AtomicInteger: 400000
synchronized:  400000
tryLock for 100 ms while another thread holds it: false

What this code does

  • Four threads add 100,000 each. The volatile counter loses updates, because volatileCount++ is still read, add, write; your number will differ on every run. AtomicInteger and synchronized both give exactly 400000.
  • tryLock(100, TimeUnit.MILLISECONDS) gives up and returns false while another thread holds the lock. A thread waiting to enter synchronized cannot give up like that.

ReentrantLock does the same job and adds tryLock with a timeout, lockInterruptibly, an optional fair mode and several Condition objects, but you must call unlock() in a finally block. The usual answer: use synchronized by default, and ReentrantLock when you need one of its extras.

volatile gives visibility: a write by one thread is seen by later reads in other threads. It does not make count++ atomic, because ++ is a read, an add and a write. Atomic classes such as AtomicInteger give visibility and atomic read-modify-write, using compare-and-set. Use volatile for a flag that one thread sets and others read; use an atomic class for a counter.

Runnable versus Callable, sleep versus wait

A Runnable has void run(): no result and no checked exceptions. A Callable<V> has V call() throws Exception: it returns a value and may throw.

Example 2 · Callable results and exceptions; wait releases the lock, sleep does not

CallableAndWaitDemo.javaJava
import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;
public class CallableAndWaitDemo {    static final Object lock = new Object();
    // how long main waits to enter synchronized (lock) while 'other' runs    static long millisToEnter(Thread other) throws InterruptedException {        other.start();        Thread.sleep(50);        long t0 = System.nanoTime();        synchronized (lock) { }        long ms = (System.nanoTime() - t0) / 1_000_000;        other.join();        return ms;    }
    public static void main(String[] args) throws Exception {        // Runnable: no result, no checked exception. Callable: both.        ExecutorService pool = Executors.newFixedThreadPool(2);        Runnable log = () -> System.out.println("Runnable ran, returns nothing");        Callable<Integer> fee = () -> 45_000 + 12_000;        Callable<Integer> broken = () -> { throw new Exception("fee server down"); };
        pool.submit(log).get();        System.out.println("Callable returned " + pool.submit(fee).get());        try {            pool.submit(broken).get();        } catch (ExecutionException e) {            System.out.println("Callable threw: " + e.getCause().getMessage());        }        pool.shutdown();
        // wait() releases the lock while waiting; sleep() keeps it        Thread waiter = new Thread(() -> {            synchronized (lock) {                try { lock.wait(300); } catch (InterruptedException e) { /* exit */ }            }        });        Thread sleeper = new Thread(() -> {            synchronized (lock) {                try { Thread.sleep(300); } catch (InterruptedException e) { /* exit */ }            }        });        System.out.println("While the other thread is in wait(300): main waited "                + (millisToEnter(waiter) < 100 ? "under 100 ms" : "a long time"));        System.out.println("While the other thread is in sleep(300): main waited "                + (millisToEnter(sleeper) < 100 ? "under 100 ms" : "a long time"));    }}
Output
Runnable ran, returns nothing
Callable returned 57000
Callable threw: fee server down
While the other thread is in wait(300): main waited under 100 ms
While the other thread is in sleep(300): main waited a long time

What this code does

  • submit(Runnable) returns a Future whose get() only waits. The Callable returns 57000; when a Callable throws, get() throws ExecutionException with the original exception as its cause.
  • While the other thread is inside lock.wait(300), main enters synchronized (lock) almost at once, because wait released the lock. During Thread.sleep(300) the lock stays taken, so main has to wait. main sleeps 50 ms first so that the other thread takes the lock before it.

ExecutorService.submit accepts both and returns a Future; for a Callable, get() returns the result or throws an ExecutionException that wraps the task's exception.

Thread.sleep(ms) pauses the current thread and keeps every lock it holds. obj.wait() must be called while holding obj's lock (otherwise IllegalMonitorStateException), releases that lock while it waits, and returns after notify or notifyAll on the same object, or after its timeout. Always call wait() inside a while loop that checks the condition again.

Deadlock conditions and thread pool sizing

Deadlock in one breath: four conditions must all hold, namely mutual exclusion, hold and wait, no preemption and circular wait. Prevent it with lock ordering, tryLock with a timeout, or a single lock, and never call unknown code while holding a lock.

Example 3 · A starting pool size for three kinds of work

PoolSizeDemo.javaJava
public class PoolSizeDemo {    // a common starting formula: threads = cores * (1 + wait time / compute time)    static int poolSize(int cores, double waitMs, double computeMs) {        return (int) Math.round(cores * (1 + waitMs / computeMs));    }
    static void show(String job, int cores, double waitMs, double computeMs) {        System.out.printf("%-28s wait %3.0f ms, compute %3.0f ms -> %d threads%n",                job, waitMs, computeMs, poolSize(cores, waitMs, computeMs));    }
    public static void main(String[] args) {        int cores = 8;   // in real code: Runtime.getRuntime().availableProcessors()        show("Resize photos (CPU only)", cores, 0, 50);        show("Generate PDFs (mostly CPU)", cores, 10, 40);        show("Call bank APIs (mostly wait)", cores, 90, 10);    }}
Output
Resize photos (CPU only)     wait   0 ms, compute  50 ms -> 8 threads
Generate PDFs (mostly CPU)   wait  10 ms, compute  40 ms -> 10 threads
Call bank APIs (mostly wait) wait  90 ms, compute  10 ms -> 80 threads

What this code does

  • With 8 cores, CPU-only work gets 8 threads. Work that waits 90 ms for every 10 ms of computing gets 80, because most of those threads are just waiting at any moment.
  • Real code reads the core count with Runtime.getRuntime().availableProcessors(); a fixed 8 keeps this output the same on every machine. Treat the result as a first guess and measure.

Find it with a thread dump ("Found one Java-level deadlock") or ThreadMXBean.findDeadlockedThreads().

Pool size depends on what the tasks do. CPU-bound work, such as calculations, gains nothing from more threads than cores, so start with the number of cores. I/O-bound work, such as database or network calls, spends most of its time waiting, so more threads help. A common starting point is threads = cores × (1 + wait time ÷ compute time); then measure under real load and adjust.

ConcurrentHashMap internals in simple terms

ConcurrentHashMap is a thread-safe hash map that never locks the whole map. Since Java 8, reads take no lock, putting a key into an empty bucket uses compare-and-set, and changing a bucket that already has entries locks only that bucket.

Example 4 · ConcurrentHashMap: merge, computeIfAbsent and null

ChmDemo.javaJava
import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.atomic.AtomicInteger;
public class ChmDemo {    public static void main(String[] args) throws InterruptedException {        ConcurrentHashMap<String, Integer> votes = new ConcurrentHashMap<>();        List<String> ballots = List.of("Asha", "Ravi", "Asha", "Zoya", "Asha", "Ravi");
        // 4 counting threads, each counting every ballot 1000 times        Thread[] counters = new Thread[4];        for (int i = 0; i < counters.length; i++) {            counters[i] = new Thread(() -> {                for (int r = 0; r < 1000; r++) {                    for (String name : ballots) {                        votes.merge(name, 1, Integer::sum);     // atomic read-add-write per key                    }                }            });            counters[i].start();        }        for (Thread t : counters) t.join();        System.out.println("Votes: " + new TreeMap<>(votes));
        // computeIfAbsent runs the loader at most once per key, even under many threads        ConcurrentHashMap<String, String> cache = new ConcurrentHashMap<>();        AtomicInteger loads = new AtomicInteger();        Thread[] readers = new Thread[4];        for (int i = 0; i < readers.length; i++) {            readers[i] = new Thread(() -> {                for (String pnr : List.of("PNR1", "PNR2", "PNR1")) {                    cache.computeIfAbsent(pnr, k -> { loads.incrementAndGet(); return k + ":CNF"; });                }            });            readers[i].start();        }        for (Thread t : readers) t.join();        System.out.println("Cache: " + new TreeMap<>(cache) + ", loader calls: " + loads.get());
        try {            votes.put("Nobody", null);        } catch (NullPointerException e) {            System.out.println("null values are not allowed in ConcurrentHashMap");        }    }}
Output
Votes: {Asha=12000, Ravi=8000, Zoya=4000}
Cache: {PNR1=PNR1:CNF, PNR2=PNR2:CNF}, loader calls: 2
null values are not allowed in ConcurrentHashMap

What this code does

  • merge(name, 1, Integer::sum) is one atomic step per key, so four threads counting the same ballots never lose a vote: 3 Asha ballots × 1000 rounds × 4 threads = 12000.
  • computeIfAbsent ran the loader only twice, once per PNR, although four threads asked at the same time. put with a null value throws NullPointerException.

Threads working on different keys rarely wait for each other. Java 7 instead split the map into 16 "segments", each with its own lock.

Points interviewers look for:

  • No null keys or values, so a null from get always means "not there".
  • merge, compute and computeIfAbsent are atomic per key, but get followed by put is still a race.
  • Iterators are weakly consistent: they never throw ConcurrentModificationException and may or may not show recent changes.
  • size() is only an estimate while other threads change the map; long bucket chains turn into small trees, and resizing is shared between threads.

Next step

Check your understanding

12 quick questions