Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Concurrency

    Thread Pools and Executors

    A thread pool is a set of reusable worker threads plus a task queue. You submit tasks; free workers pick them up.

    Chapter 2 of 125 min readOften asked in interviews

    The Plain Picture#

    A restaurant doesn't hire a new cook for every order and fire them afterwards. It keeps a fixed team of cooks and an order rail: orders are clipped to the rail, and whichever cook is free takes the next one.

    The Real Names#

    • A thread pool is a set of reusable worker threads plus a task queue. You submit tasks; free workers pick them up.

    • ExecutorService is the interface; Executors has factory methods: newFixedThreadPool(n), newCachedThreadPool(), newSingleThreadExecutor(), newScheduledThreadPool(n), newVirtualThreadPerTaskExecutor() (Ch 11).

    • submit(task) returns a Future — a receipt for a result that will exist later. future.get() waits for it (and rethrows any exception, wrapped in ExecutionException).

    • A Callable<V> is like Runnable but returns a value and may throw checked exceptions.

    • invokeAll(tasks) submits many tasks and waits for all of them.

    • Always shut pools down — shutdown() (finish queued work, accept no more) or shutdownNow() (interrupt everything) — or use try-with-resources (Java 19+; ExecutorService is AutoCloseable — Exceptions and Generics Ch 4). A forgotten pool's non-daemon threads keep the JVM alive.

    Under the Hood#

    Eight 500 ms jobs (standing in for AI calls), on pools of different sizes:

    Java
    List<Callable<String>> jobs = new ArrayList<>();
    
    for (int i = 1; i <= 8; i++) {
        int id = i;
        jobs.add(() -> {
            Thread.sleep(500);
            return "quiz-" + id;
        });
    }
    
    List<Future<String>> done = pool8.invokeAll(jobs); // 8 threads
    
    two.invokeAll(jobs); // 2 threads
    Output
    8 x 500ms jobs on 8 threads: 505 ms, first=quiz-1
    8 x 500ms jobs on 2 threads: 2020 ms

    With 8 threads all jobs wait at the same time — 500 ms total. With 2, they go in 4 waves of 2 — 2,000 ms.

    How big should a pool be?#

    It depends on whether the work is CPU-bound or I/O-bound (Operating Systems Ch 4):

    Work typeRule of thumbWhy
    CPU-bound (image resizing, parsing, maths)threads ≈ number of cores (Runtime.getRuntime().availableProcessors())more threads can't run at the same time; they only add context switches
    I/O-bound (HTTP calls, database queries)threads ≈ cores × (1 + wait time ÷ compute time)while one thread waits, others can use the core

    Example: 8 cores, each AI request spends 3,000 ms waiting and 30 ms computing → 8 × (1 + 100) ≈ 800 threads. That's a lot of 1 MB stacks — which is exactly the problem virtual threads (Ch 11) solve.

    What's inside newFixedThreadPool — ThreadPoolExecutor#

    Java
    new ThreadPoolExecutor(
        corePoolSize, // threads kept alive even when idle
        maximumPoolSize, // upper limit under load
        keepAliveTime,
        unit, // how long extra idle threads survive
        workQueue, // where tasks wait: bounded (ArrayBlockingQueue) or unbounded (LinkedBlockingQueue)
        rejectionHandler
    ); // what to do when the queue is full and max threads are busy

    The order it uses: fill up to core threads → then queue tasks → only when the queue is full, grow toward max threads → then reject.

    Production gotcha: Executors.newFixedThreadPool(n) uses an unbounded queue. Under overload, tasks pile up in memory until the process is OOM-killed (Operating Systems Ch 5). Production services build ThreadPoolExecutor with a bounded queue and a rejection policy (e.g. return HTTP 503 — "slow down" — instead of dying). This is backpressure: pushing back on callers instead of accepting infinite work.

    Check yourself

    4 questions
    1

    Why use a thread pool rather than a new thread per task?

    Show answer

    Creating threads is expensive (memory and time); pools reuse a bounded number of them and queue the rest.

    2

    What's a Future, and what does get() do?

    Show answer

    A handle to a result that will be available later; get() blocks until it's ready (rethrowing failures as ExecutionException).

    3

    How would you size a pool for CPU-bound work? For I/O-bound work?

    Show answer

    About the number of cores; cores × (1 + wait/compute).

    4

    Why can Executors.newFixedThreadPool be dangerous in production?

    Show answer

    Its queue is unbounded, so under overload tasks pile up in memory until the process runs out of memory.