Skip to the page

Concurrency · mid

Executors and thread pools

Pool size comes from arrival rate and wait time. Default pools have unbounded queues. submit hides exceptions. A pool task must never wait for another task in the same pool.

The notes

What you must know

  • Little's law: calls in flight = arrival rate times time. 500 requests a second at 0.2 seconds gives 100 in flight. Add headroom and size for p99 latency.
  • Rules of thumb: CPU-bound work, about the number of cores. I/O-bound work, cores times (1 + wait time / compute time).
  • newFixedThreadPool has an unbounded queue. When a partner slows down, tasks pile up in memory and latency grows silently.
  • Build a ThreadPoolExecutor yourself: a bounded queue, named threads (a ThreadFactory) and a chosen rejection policy. AbortPolicy is the default.
  • Threads above the core size are created only when the queue is full. With a 10,000 queue the pool stays at its core size until the queue fills.
  • submit() stores an exception in the Future and shows it only on get(). execute() passes it to the UncaughtExceptionHandler. Nobody calling get means silent failures.
  • shutdown() does not wait. Use awaitTermination, or on Java 19+ try-with-resources on the executor. "Finished in 4 seconds" may only mean the tasks were queued.
  • Thread-starvation deadlock: parent tasks fill every thread and each waits for child tasks queued behind them. jstack does not report it as a deadlock because no lock cycle exists. Use separate pools, or compose with CompletableFuture. Metrics: active threads, queue size, rejections, call latency. Add timeouts on every partner call and a separate limit (a Semaphore) for the partner's rate.

The red pen

Common traps: mistake → fix

  • Mistake: More threads always means more throughput

    Fix: beyond the downstream limit it only adds queueing and memory.

  • Mistake: No exception in logs means the task worked

    Fix: submit() hides exceptions in the Future.

  • Mistake: A deadlock always shows in jstack

    Fix: starvation deadlock has no lock cycle.

Easy to hard

Questions interviewers ask, easy to hard

  1. How many threads for 500 requests a second to an API that takes 200 ms?
  2. What is wrong with newFixedThreadPool in production?
  3. Why did a job log "finished" while 5% of SMS were missing?
  4. Why does a batch job hang with zero CPU after the partition count increases?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview