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.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe 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).
newFixedThreadPoolhas 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 onget().execute()passes it to the UncaughtExceptionHandler. Nobody calling get means silent failures.shutdown()does not wait. UseawaitTermination, 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
- How many threads for 500 requests a second to an API that takes 200 ms?
- What is wrong with newFixedThreadPool in production?
- Why did a job log "finished" while 5% of SMS were missing?
- Why does a batch job hang with zero CPU after the partition count increases?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.