Autocoder

Java Concurrency Utilities Interview Questions

Last updated 2026-11-19

Once the basics of threads are clear, interviews move to java.util.concurrent: thread pools, futures, locks, synchronisers and concurrent collections. The questions here are about choosing the right tool and knowing its failure modes, such as unbounded queues, blocked common pools and lost interrupts.

The examples target Java 17, with notes for Java 19 and later where ExecutorService became AutoCloseable. The foundations are on the multithreading page.

Packagejava.util.concurrent and its atomic and locks subpackages
Java version17 and later
Typical roundsTechnical rounds for 2 or more years of experience

Pick the tool

Java Concurrency Utilities Interview Questions: questions with worked answers

  1. 1

    Explain the parameters of ThreadPoolExecutor and the order in which it uses them.

    medium

    The constructor takes corePoolSize, maximumPoolSize, keepAliveTime, a work queue, a thread factory and a rejection handler. A new task starts a new thread while fewer than core threads exist. After that it goes into the queue. Only when the queue is full does the pool create threads up to the maximum, and when both are full the handler runs (AbortPolicy throws RejectedExecutionException by default).

    java
    ThreadPoolExecutor ex = new ThreadPoolExecutor(
        2, 4, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(2));
    // tasks 1,2 -> core threads; 3,4 -> queue; 5,6 -> extra threads; 7 -> rejected
  2. 2

    What is wrong with Executors.newFixedThreadPool and newCachedThreadPool in production?

    medium

    newFixedThreadPool uses an unbounded LinkedBlockingQueue, so a slow consumer lets the queue grow until memory runs out, and maximum size is irrelevant. newCachedThreadPool has an unbounded maximum thread count and a SynchronousQueue, so a burst of tasks can create thousands of threads. Construct ThreadPoolExecutor directly with a bounded queue and an explicit rejection policy.

  3. 3

    How do you shut down an ExecutorService correctly?

    easy

    shutdown() stops accepting new tasks and lets queued ones finish. shutdownNow() interrupts running tasks and returns the tasks that never started. The standard pattern is shutdown, then awaitTermination with a timeout, then shutdownNow if it did not finish. Since Java 19 ExecutorService implements AutoCloseable, so try-with-resources does that for you.

    java
    ex.shutdown();
    if (!ex.awaitTermination(30, TimeUnit.SECONDS)) {
        ex.shutdownNow();
    }
  4. 4

    Runnable versus Callable versus Future.

    easy

    Runnable.run returns nothing and cannot throw checked exceptions. Callable.call returns a value and may throw. submit(Callable) returns a Future whose get() blocks until the result is ready; an exception in the task is wrapped in ExecutionException. Future.cancel(true) interrupts the task. Future cannot be chained, which is why CompletableFuture exists.

  5. 5

    How does CompletableFuture compose results? Predict the output.

    medium

    supplyAsync runs a task on the common ForkJoinPool by default (or on an executor you supply). thenApply transforms the result, thenCompose flattens a dependent future, thenCombine joins two independent ones, and exceptionally or handle recovers from errors. join waits and throws unchecked exceptions.

    java
    CompletableFuture<Integer> a = CompletableFuture.supplyAsync(() -> 6);
    CompletableFuture<Integer> b = CompletableFuture.supplyAsync(() -> 7);
    int r = a.thenCombine(b, (x, y) -> x * y)
             .thenApply(v -> v + 0)
             .join();
    System.out.println(r);        // 42
    String s = CompletableFuture.<String>supplyAsync(() -> { throw new IllegalStateException(); })
            .exceptionally(t -> "fallback").join();
    System.out.println(s);        // fallback
  6. 6

    What is the danger of the common ForkJoinPool with CompletableFuture and parallel streams?

    medium

    They share a pool sized to about the number of cores minus one. Blocking calls such as database or HTTP requests tie up its few threads and stall every other user of the pool, including parallel streams. Pass your own executor to the async methods for blocking work, and keep common-pool tasks short and CPU-bound.

  7. 7

    CountDownLatch, CyclicBarrier, Semaphore and Phaser: how do they differ?

    medium

    CountDownLatch starts at N and threads call countDown; waiters in await are released once, when it reaches zero, and it cannot be reset. CyclicBarrier makes a fixed number of threads wait for each other and can be reused, optionally running a barrier action. Semaphore holds permits to limit concurrent access to a resource, such as five database connections. Phaser is a flexible, reusable barrier with a changing number of parties.

    java
    CountDownLatch done = new CountDownLatch(3);
    for (int i = 0; i < 3; i++) new Thread(() -> { /* work */ done.countDown(); }).start();
    done.await();             // continues after all three call countDown
  8. 8

    ReentrantLock versus synchronized.

    medium

    Both are reentrant and give mutual exclusion and visibility. ReentrantLock adds tryLock, timed and interruptible lock attempts, optional fairness and multiple Condition objects, but you must release it in a finally block yourself. synchronized releases automatically even on exceptions and is simpler. Choose ReentrantLock only when you need those extra features.

    java
    lock.lock();
    try {
        // critical section
    } finally {
        lock.unlock();
    }
    if (lock.tryLock(1, TimeUnit.SECONDS)) { try { /* ... */ } finally { lock.unlock(); } }
  9. 9

    When would you use ReadWriteLock or StampedLock?

    hard

    ReentrantReadWriteLock lets many readers hold the lock simultaneously while a writer is exclusive, which pays off when reads heavily outnumber writes and the critical section is not tiny. StampedLock adds optimistic reads: read without a lock, then validate the stamp, retrying under a real read lock if a write intervened. It is not reentrant and does not support Conditions.

  10. 10

    How do atomic classes work, and when is LongAdder better?

    medium

    AtomicInteger and friends use compare-and-swap, a CPU instruction that updates a value only if it still equals what you expect, retrying on failure, so there is no lock. Under heavy contention many threads retry. LongAdder keeps several cells and sums them on read, giving much higher throughput for write-heavy counters, at the cost of a sum that is not an atomic snapshot. The ABA problem, where a value changes A to B and back, is addressed by AtomicStampedReference.

  11. 11

    Use ConcurrentHashMap atomic methods for a word count. Why is get-then-put wrong?

    medium

    Between get and put another thread can update the same key, so increments are lost. merge, compute and putIfAbsent perform the whole read-modify-write atomically for that key. Keep the function passed in short and free of side effects, since it runs while the bin is locked.

    java
    ConcurrentHashMap<String,Integer> m = new ConcurrentHashMap<>();
    for (String w : "a b a".split(" ")) m.merge(w, 1, Integer::sum);
    System.out.println(m);   // {a=2, b=1}
    // wrong: m.put(w, m.getOrDefault(w, 0) + 1);
  12. 12

    When do you use CopyOnWriteArrayList?

    easy

    It copies the whole array on every write and iterates over an immutable snapshot, so iteration never throws ConcurrentModificationException and needs no locking. It fits read-mostly lists such as listener registries. It is a bad choice for lists that change often or are large, because each write is O(n).

  13. 13

    Compare the BlockingQueue implementations.

    medium

    ArrayBlockingQueue is bounded and array-backed. LinkedBlockingQueue is optionally bounded (unbounded by default). PriorityBlockingQueue is unbounded and ordered. SynchronousQueue has no capacity and hands each item directly from a producer to a consumer, as in cached pools. DelayQueue releases elements only after their delay has expired. LinkedTransferQueue adds a transfer method that waits for a consumer.

  14. 14

    How does ForkJoinPool work and what is work stealing?

    hard

    A ForkJoinPool runs RecursiveTask or RecursiveAction subtasks that split a problem (fork) and combine the results (join). Each worker owns a deque; it takes its own newest tasks, while idle workers steal the oldest tasks from the other end of another worker's deque, keeping all cores busy with little contention. Choose a sensible threshold below which a task computes directly.

    java
    class Sum extends RecursiveTask<Long> {
        final int[] a; final int lo, hi;
        Sum(int[] a, int lo, int hi) { this.a = a; this.lo = lo; this.hi = hi; }
        protected Long compute() {
            if (hi - lo <= 1000) { long s = 0; for (int i = lo; i < hi; i++) s += a[i]; return s; }
            int mid = (lo + hi) >>> 1;
            Sum left = new Sum(a, lo, mid);
            left.fork();
            return new Sum(a, mid, hi).compute() + left.join();
        }
    }
  15. 15

    How should you size a thread pool?

    medium

    For CPU-bound work use about the number of cores, plus one. For work that blocks on I/O, a common estimate is cores * (1 + wait time / compute time), but measure instead of trusting the formula. Several pools, one per kind of work, keep slow dependencies from starving fast ones, and virtual threads on Java 21 remove most of the need to size I/O pools.

  16. 16

    scheduleAtFixedRate versus scheduleWithFixedDelay?

    medium

    scheduleAtFixedRate starts runs at fixed intervals measured from the start of each run, so a slow run delays the next ones and they may bunch up. scheduleWithFixedDelay waits the given delay after each run finishes. If a task throws, further executions are suppressed, so catch exceptions inside the task.

Frequently asked questions

Which concurrency utility is asked most?

ExecutorService with ThreadPoolExecutor parameters, then CountDownLatch versus CyclicBarrier and ConcurrentHashMap internals.

Is CompletableFuture better than Future?

Yes for composition and non-blocking code; Future.get blocks and cannot be chained.

What replaced Hashtable and synchronizedMap?

ConcurrentHashMap, which supports concurrent reads and fine-grained writes. Details are on the HashMap internals page.

Are virtual threads a replacement for pools?

For blocking tasks, a virtual-thread-per-task executor replaces a sized pool. CPU-bound work still needs a bounded pool.

Related guides

More in Programming Language Interview Questions by Language

See all in this section