Medium java java-21

A fixed thread pool of 3 threads gets 10 tasks. How do they run?

The 30 second answer

With Executors.newFixedThreadPool(3), the first three tasks each get a new thread and start at once. The other seven wait in the pool's unbounded queue. Whenever a thread finishes a task, it takes the next one from the queue, so the work runs in waves of three on the same three threads. No extra threads are created and nothing is rejected. Start order roughly follows submission, but finish order is not guaranteed.

Could you say this in an interview?

What the pool is. The Executors.newFixedThreadPool(n) Javadoc says it "reuses a fixed number of threads operating off a shared unbounded queue". At most n threads are active, and extra tasks "will wait in the queue until a thread is available". Under the hood it is a ThreadPoolExecutor with core size and max size both set to 3 and a LinkedBlockingQueue with no capacity limit.

Step by step for 10 tasks:

  1. Tasks 1, 2 and 3 arrive. The pool has fewer than 3 threads, so the ThreadPoolExecutor rules say it creates a new thread for each, even if another worker is idle. Threads are created lazily, on submit, not when the pool is built.
  2. Tasks 4 to 10 arrive while all three threads are busy. They go into the queue.
  3. Each thread, after finishing its task, pulls the next task from the queue. The pool keeps the same three threads for its whole life.
  4. shutdown() stops new submissions but lets the queued tasks finish; awaitTermination waits for them.

I ran this on OpenJDK 21.0.13 with tasks that sleep 100 ms. Tasks 1 to 3 started at about 3 ms, tasks 4 to 6 at about 115 ms, tasks 7 to 9 at about 215 ms and task 10 at about 316 ms, all on pool-1-thread-1 to pool-1-thread-3. That is four waves for ten tasks on three threads.

ExecutorService pool = Executors.newFixedThreadPool(3);
for (int i = 1; i <= 10; i++) {
    int id = i;
    pool.execute(() -> {
        System.out.println("task " + id + " on " + Thread.currentThread().getName());
        sleep(100);
    });
}
pool.shutdown();
pool.awaitTermination(5, TimeUnit.SECONDS);

What to say about order. Tasks leave the queue in FIFO order, so they start roughly in submission order. Which thread runs which task, and the order they finish in, depend on scheduling and task length. If the result order matters, keep the Future objects in a list and read them in order, or use invokeAll.

The production caveat. The unbounded queue is the risk: if tasks arrive faster than three threads can finish them, the queue grows until memory runs out, and latency grows with it. For a real service I build a ThreadPoolExecutor directly with a bounded queue and an explicit rejection policy, so overload shows up as a fast, visible failure instead of a slow memory leak.

Alternate interview scenarios

"Same 10 tasks, but the pool has core size 3, max size 5 and a queue of capacity 2. What happens?"

The ThreadPoolExecutor rules are: below core size, start a new thread; otherwise queue the task; if the queue is full, start a new thread up to max size; if that is not possible either, reject the task. So tasks 1 to 3 start three core threads, tasks 4 and 5 fill the queue, tasks 6 and 7 start threads 4 and 5, and tasks 8, 9 and 10 are rejected. With the default AbortPolicy the execute call throws RejectedExecutionException. I verified exactly this on Java 21: tasks 8, 9 and 10 were rejected and tasks 6 and 7 ran on pool-2-thread-4 and pool-2-thread-5. The surprise for many people is that the pool grows past core size only when the queue is full, so with an unbounded queue max size never matters. CallerRunsPolicy is the usual alternative: the submitting thread runs the task itself, which slows the producer down.

"One of the 10 tasks throws an exception. Does the pool lose a thread?"

With execute, the exception escapes the task, the worker thread dies and the stack trace goes to the uncaught exception handler; the ThreadPoolExecutor then starts a replacement thread, so the pool size is kept, but you pay for a new thread. With submit, the exception is captured in the Future and the thread survives. The other nine tasks run either way.

Sources (3)
  1. Executors Javadoc (Java 21): newFixedThreadPooldocs.oracle.com
  2. ThreadPoolExecutor Javadoc (Java 21): core and maximum pool sizes, queuing, rejected tasksdocs.oracle.com
  3. ExecutorService Javadoc (Java 21): shutdown, awaitTermination, invokeAlldocs.oracle.com