Thread Pool & ExecutorService
Thread pool concepts, fixed/cached/single/scheduled thread pools, rejection policies
- Explain why thread pools outperform creating raw threads
- Configure ThreadPoolExecutor parameters: corePoolSize, maxPoolSize, queue, policy
- Choose between fixed, cached, single, and scheduled executors
Table of Contents
- What is a Thread Pool?
- Why Thread Pools Exist — Advantages
- The Executor Framework
- ThreadPoolExecutor — Deep Dive
- Constructor Parameters Explained
- Thread Pool Execution Flow
- ThreadPoolExecutor Lifecycle
- Rejection Policies
- ThreadFactory
- Complete Code Example
- Sizing a Thread Pool — The Interview Question
- Thread Pool Sizing Formula
- Memory-Based Sizing
- Common Mistakes
- Best Practices
- Interview Notes
- Practice Questions
- Summary
1. What is a Thread Pool?
Overview
A Thread Pool is a managed collection of pre-created threads — often called worker threads — that are kept alive and ready to execute submitted tasks. Instead of creating a new thread for every task (and destroying it when the task finishes), the pool reuses existing threads, dramatically reducing overhead.
Real-World Analogy
Think of a restaurant kitchen. Instead of hiring a new chef for each customer order (creating a thread) and firing them when the order is done (destroying the thread), the restaurant keeps a fixed team of chefs (the thread pool). When an order comes in, an available chef takes it. When the order is ready, that chef is immediately ready for the next order. If all chefs are busy, new orders wait in a queue (the work queue).
Definition
A Thread Pool is a collection of worker threads maintained by an executor framework. Tasks are submitted to the pool, assigned to an available thread, executed, and the thread is then returned to the pool to await new tasks — avoiding the cost of repeated thread creation and destruction.
How Reuse Works
1Thread Pool2┌──────────────────────────────┐3│ Thread-0 │ Thread-1 │ Thread-2 │ ← pre-created, waiting4└──────────────────────────────┘5 ↑ Task submitted → assigned to free thread6 ↑ Task completes → thread returns to pool2. Why Thread Pools Exist Advantages
Problem Without Thread Pools
Without a thread pool, the typical pattern is:
1// Without thread pool — naïve approach2for (Task task : tasks) {3 new Thread(() -> task.execute()).start(); // new thread every time4}This causes three serious problems:
| Problem | Explanation |
|---|---|
| Thread creation overhead | Every new Thread(...) allocates stack memory, a program counter, and other per-thread resources. This takes measurable time. |
| Lifecycle management burden | Developer must manually track states: new → runnable → running → waiting → terminated. |
| Uncontrolled context switching | Creating 100 threads on a 2-core CPU means the OS constantly saves/restores thread state — context switching — wasting CPU cycles. |
Advantage 1 Thread Creation Time Saved
When a thread is created, the JVM must:
- Allocate a thread stack (default 512KB–1MB per thread on most JVMs)
- Initialise a program counter (PC register)
- Set up the thread's native OS handle
This allocation takes time. A thread pool pre-allocates these resources once at startup and reuses them indefinitely.
Advantage 2 Lifecycle Management Abstracted
The Executor Framework fully manages:
- Starting threads
- Putting them into waiting/runnable states
- Assigning tasks
- Terminating threads when the pool shuts down
The developer only submits tasks. The framework handles everything else.
Advantage 3 Performance Improvement via Controlled Concurrency
12 CPU cores, 100 threads (without pool)2══════════════════════════════════════3CPU: [Thread-1][Thread-2][CONTEXT SWITCH][Thread-3][Thread-4][CONTEXT SWITCH]...4 ↑ actual work ↑ idle (saving/restoring state)5
62 CPU cores, 2 threads (with pool matching cores)7══════════════════════════════════════8CPU: [Thread-0][Thread-0][Thread-0][Thread-0]... ← near-zero context switching9 ↑ continuous processing3. The Executor Framework
Package
All executor classes and interfaces live in:
1java.util.concurrentInterface Hierarchy
Key Interfaces
| Interface | Purpose | Key Methods |
|---|---|---|
Executor | Simplest contract — execute a Runnable | execute(Runnable) |
ExecutorService | Extends Executor; adds lifecycle management | submit(), shutdown(), shutdownNow(), isTerminated() |
ScheduledExecutorService | Extends ExecutorService; adds delayed/periodic task support | schedule(), scheduleAtFixedRate() |
Key Classes
| Class | Purpose |
|---|---|
ThreadPoolExecutor | Fully configurable, general-purpose thread pool |
ForkJoinPool | Work-stealing pool optimised for divide-and-conquer tasks |
Executors | Factory class with convenience methods (newFixedThreadPool, newCachedThreadPool, etc.) |
ThreadPoolExecutor — the most important and configurable implementation, and the most common subject of interviews.4. ThreadPoolExecutor Deep Dive
What It Is
ThreadPoolExecutor is the core, fully-configurable thread pool implementation in Java. It allows precise control over:
- Minimum and maximum number of threads
- How long idle threads live
- The type and capacity of the work queue
- How new threads are named and configured
- What happens when tasks cannot be accepted
Why Use It Directly?
The Executors factory class (e.g., Executors.newFixedThreadPool(n)) creates ThreadPoolExecutor instances under the hood, but with less control. Using ThreadPoolExecutor directly lets you configure every parameter — which is critical for production systems.
5. Constructor Parameters Explained
Full Constructor Signature
1public ThreadPoolExecutor(2 int corePoolSize,3 int maximumPoolSize,4 long keepAliveTime,5 TimeUnit unit,6 BlockingQueue<Runnable> workQueue,7 ThreadFactory threadFactory,8 RejectedExecutionHandler handler9)Parameters At a Glance
| Parameter | Type | Purpose |
|---|---|---|
corePoolSize | int | Minimum threads always kept alive in the pool |
maximumPoolSize | int | Maximum threads ever allowed in the pool |
keepAliveTime | long | Time idle threads (above core) survive before termination |
unit | TimeUnit | Unit of keepAliveTime (e.g., SECONDS, MINUTES) |
workQueue | BlockingQueue | Queue for tasks waiting to be executed |
threadFactory | ThreadFactory | Factory to create new threads (custom naming, priority, daemon flag) |
handler | RejectedExecutionHandler | What to do when a task cannot be accepted |
5.1 `corePoolSize`
Definition: The number of threads that are created immediately when the pool is initialised (or on first use) and kept alive even when idle.
1int corePoolSize = 3;2// → 3 threads are created and permanently present in the pool.3// Even with no tasks, these 3 threads sit and wait.allowCoreThreadTimeOut(true).5.2 `allowCoreThreadTimeOut` (Property, Not Constructor Parameter)
This is a setter method called on the ThreadPoolExecutor object after construction:
1executor.allowCoreThreadTimeOut(true);| Value | Behaviour |
|---|---|
false (default) | Core threads live forever, regardless of keepAliveTime |
true | Core threads are also subject to keepAliveTime termination when idle |
keepAliveTime = 5 (minutes), core threads will not be terminated unless you explicitly call executor.allowCoreThreadTimeOut(true). Many developers forget this and wonder why idle threads are not being cleaned up.5.3 `keepAliveTime` and `unit`
Definition: The maximum time that excess idle threads (threads above corePoolSize, or all threads if allowCoreThreadTimeOut(true)) will wait for new tasks before being terminated.
1long keepAliveTime = 10;2TimeUnit unit = TimeUnit.MINUTES;3// → Any thread idle for more than 10 minutes gets terminatedTimeUnit options: NANOSECONDS, MICROSECONDS, MILLISECONDS, SECONDS, MINUTES, HOURS, DAYS
5.4 `maximumPoolSize`
Definition: The absolute upper limit on the number of threads that can exist in the pool simultaneously.
1int corePoolSize = 3; // always-present threads2int maximumPoolSize = 5; // can temporarily grow to 5 under loadWhen are threads above corePoolSize created?
New threads above corePoolSize are created only when:
- All current threads are busy, AND
- The work queue is full, AND
- The current thread count is less than
maximumPoolSize
corePoolSize is exhausted. The pool first tries to queue the task. Only when the queue is also full does the pool attempt to create additional threads (up to maximumPoolSize).5.5 `workQueue` (BlockingQueue)
Definition: A thread-safe queue where tasks wait when all core threads are busy.
◆ Two Types of Work Queues
| Type | Class | Behaviour |
|---|---|---|
| Bounded | ArrayBlockingQueue<>(capacity) | Fixed maximum size. Preferred — gives full control. |
| Unbounded | LinkedBlockingQueue<>() | No size limit. Tasks accumulate without bound — can cause OutOfMemoryError. |
1// Bounded — recommended2BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(100);3
4// Unbounded — use with caution5BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();LinkedBlockingQueue with no capacity argument) makes maximumPoolSize effectively irrelevant — the queue never fills, so extra threads are never created. It can also cause memory exhaustion under heavy load.5.6 `threadFactory`
Definition: An interface with one method — newThread(Runnable r) — that controls how new threads in the pool are created.
Why customise it?
- Set meaningful thread names (visible in thread dumps and profilers)
- Set thread priority
- Set daemon vs non-daemon
1class MyCustomThreadFactory implements ThreadFactory {2 @Override3 public Thread newThread(Runnable r) {4 Thread thread = new Thread(r);5 thread.setName("my-pool-thread-" + System.currentTimeMillis());6 thread.setPriority(Thread.NORM_PRIORITY); // 5 — normal priority7 thread.setDaemon(false); // non-daemon thread8 return thread;9 }10}"order-processor-1" are far more useful than the default "pool-1-thread-1".5.7 `handler` (RejectedExecutionHandler)
Definition: Called when a task cannot be accepted by the pool — i.e., all threads are busy, the queue is full, and maximumPoolSize is already reached.
Four built-in policies are provided (see Section 8).
6. Thread Pool Execution Flow
Complete Decision Flowchart
Step-by-Step Narrative
Step 1 — Core threads available: When a task arrives, the pool checks if any of the corePoolSize threads are free. If yes, the task is immediately assigned to one.
Step 2 — All core threads busy → try the queue: If all core threads are busy, the task is placed in the workQueue. This is intentional — the design philosophy is to exhaust the capacity of existing (core) threads before creating new ones. This avoids unnecessary thread proliferation.
Step 3 — Queue full → create new thread (up to maximum): Only when the queue is full does the pool create a new thread (if maximumPoolSize allows). This new thread takes the task immediately.
Step 4 — Maximum reached and queue full → reject: If even the maximumPoolSize has been reached and the queue is full, the RejectedExecutionHandler is invoked.
Step 5 — Thread completes → returns to pool: After completing a task, the thread doesn't die. It checks the queue for waiting tasks. If one exists, it picks it up. If not, it waits for new work.
Why Queue Before Creating Extra Threads?
Design Rationale:
The corePoolSize represents the "normal load" capacity — enough threads for typical workloads. The queue buffers burst traffic, giving existing threads a chance to catch up. Creating threads beyond corePoolSize is a last resort because: 1. New threads add memory overhead. 2. Once created, these threads sit idle in the pool consuming resources even after the burst subsides (until keepAliveTime expires). 3. The design keeps the pool lean and efficient under normal conditions.
7. ThreadPoolExecutor Lifecycle
States
State Descriptions
| State | Description | Accepts new tasks? | Processes queued tasks? |
|---|---|---|---|
| RUNNING | Normal operation | ✅ Yes | ✅ Yes |
| SHUTDOWN | shutdown() called | ❌ No | ✅ Yes (drains queue) |
| STOP | shutdownNow() called | ❌ No | ❌ No (attempts to interrupt) |
| TIDYING | All tasks done, threads winding down | ❌ No | ❌ No |
| TERMINATED | All done | ❌ No | ❌ No |
Key Methods
1executor.shutdown(); // Graceful: finish existing tasks, accept no new ones2executor.shutdownNow(); // Forceful: interrupt running tasks, clear queue3executor.isTerminated(); // Returns true if pool has fully shut down4executor.awaitTermination(60, TimeUnit.SECONDS); // Block until terminated or timeout`shutdown()` vs `shutdownNow()`
shutdown() | shutdownNow() | |
|---|---|---|
| New tasks accepted | No | No |
| Running tasks | Allowed to complete | Interrupted (best-effort) |
| Queued tasks | Will be executed | Returned as a List, not executed |
| Transition | RUNNING → SHUTDOWN → TERMINATED | RUNNING → STOP → TERMINATED |
| Use when | Graceful shutdown required | Immediate abort needed |
8. Rejection Policies
Triggered when: all threads busy + queue full + at maximum thread count.
Built-in Policies
Policy Comparison Table
| Policy Class | Behaviour | Use When |
|---|---|---|
AbortPolicy (default) | Throws RejectedExecutionException | You need to know when tasks are dropped |
DiscardPolicy | Silently drops the task | Task loss is acceptable (e.g., non-critical metrics) |
CallerRunsPolicy | Submitting thread executes the task | Natural back-pressure — slows down the producer |
DiscardOldestPolicy | Removes the oldest waiting task, resubmits new task | Newest tasks are more important than older ones |
Custom Rejection Handler
1class CustomRejectionHandler implements RejectedExecutionHandler {2 @Override3 public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {4 // Log the rejection for monitoring/debugging5 System.err.println("Task rejected: " + r.toString()6 + " | Executor: " + executor.toString());7
8 // Optional: write to a dead-letter queue, alert, metric increment, etc.9 }10}DiscardPolicy) makes debugging extremely difficult.9. ThreadFactory
Interface Definition
1public interface ThreadFactory {2 Thread newThread(Runnable r);3}What You Can Customise
| Property | Method | Purpose |
|---|---|---|
| Thread name | thread.setName("...") | Visible in logs, thread dumps, profilers |
| Priority | thread.setPriority(int) | 1 (MIN) to 10 (MAX), 5 is NORM |
| Daemon flag | thread.setDaemon(boolean) | true = JVM can exit even if this thread is running |
Thread Priority Constants
1Thread.MIN_PRIORITY // 12Thread.NORM_PRIORITY // 5 ← default3Thread.MAX_PRIORITY // 10Complete Custom ThreadFactory
1import java.util.concurrent.ThreadFactory;2import java.util.concurrent.atomic.AtomicInteger;3
4class MyCustomThreadFactory implements ThreadFactory {5 private final AtomicInteger threadNumber = new AtomicInteger(1);6 private final String namePrefix;7
8 public MyCustomThreadFactory(String poolName) {9 this.namePrefix = poolName + "-thread-";10 }11
12 @Override13 public Thread newThread(Runnable r) {14 Thread t = new Thread(r, namePrefix + threadNumber.getAndIncrement());15 t.setPriority(Thread.NORM_PRIORITY);16 t.setDaemon(false);17 return t;18 }19}10. Complete Code Example
Scenario
corePoolSize = 2maximumPoolSize = 4workQueuecapacity =2- Submit 7 tasks (to demonstrate core, queue, max, and rejection)
Code
1import java.util.concurrent.*;2
3public class ThreadPoolDemo {4
5 // ── Custom Thread Factory ──────────────────────────────────────────6 static class MyCustomThreadFactory implements ThreadFactory {7 private final AtomicIntegerHolder count = new AtomicIntegerHolder(0);8
9 @Override10 public Thread newThread(Runnable r) {11 Thread t = new Thread(r);12 t.setName("demo-pool-thread-" + count.incrementAndGet());13 t.setPriority(Thread.NORM_PRIORITY);14 t.setDaemon(false);15 return t;16 }17
18 // Simple wrapper to avoid importing AtomicInteger for clarity19 static class AtomicIntegerHolder {20 private int val;21 AtomicIntegerHolder(int init) { val = init; }22 int incrementAndGet() { return ++val; }23 }24 }25
26 // ── Custom Rejection Handler ───────────────────────────────────────27 static class CustomRejectionHandler implements RejectedExecutionHandler {28 @Override29 public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {30 System.out.println("⚠️ TASK REJECTED: " + r.toString());31 }32 }33
34 // ── Main ──────────────────────────────────────────────────────────35 public static void main(String[] args) throws InterruptedException {36
37 int corePoolSize = 2;38 int maxPoolSize = 4;39 long keepAliveTime = 10;40 TimeUnit unit = TimeUnit.MINUTES;41 BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(2); // bounded queue, capacity 242
43 ThreadPoolExecutor executor = new ThreadPoolExecutor(44 corePoolSize,45 maxPoolSize,46 keepAliveTime,47 unit,48 queue,49 new MyCustomThreadFactory(),50 new CustomRejectionHandler()51 );52
53 // Optional: allow core threads to also time out when idle54 // executor.allowCoreThreadTimeOut(true);55
56 int totalTasks = 7;57
58 for (int i = 1; i <= totalTasks; i++) {59 final int taskId = i;60 executor.submit(() -> {61 System.out.println("✅ Task-" + taskId62 + " processed by " + Thread.currentThread().getName());63 try {64 Thread.sleep(5000); // simulate 5-second work65 } catch (InterruptedException e) {66 Thread.currentThread().interrupt();67 }68 });69 }70
71 executor.shutdown();72 executor.awaitTermination(60, TimeUnit.SECONDS);73 System.out.println("All tasks complete. Pool terminated.");74 }75}Dry Run What Happens With 7 Tasks
| Task # | Thread Pool State | Queue State | Action Taken |
|---|---|---|---|
| Task-1 | 0 busy / 2 core | Empty | Assign to core thread-1 |
| Task-2 | 1 busy / 2 core | Empty | Assign to core thread-2 |
| Task-3 | 2 busy / 2 core | 0/2 | Queue Task-3 |
| Task-4 | 2 busy / 2 core | 1/2 | Queue Task-4 |
| Task-5 | 2 busy / 2 core | 2/2 (full) | Create thread-3, assign Task-5 |
| Task-6 | 3 busy / 4 max | 2/2 (full) | Create thread-4, assign Task-6 |
| Task-7 | 4 busy / 4 max | 2/2 (full) | REJECT → CustomRejectionHandler |
Expected Output (approximate thread names and order may vary)
1✅ Task-1 processed by demo-pool-thread-12✅ Task-2 processed by demo-pool-thread-23✅ Task-5 processed by demo-pool-thread-34✅ Task-6 processed by demo-pool-thread-45⚠️ TASK REJECTED: java.util.concurrent.FutureTask@...6✅ Task-3 processed by demo-pool-thread-1 ← picked from queue after Task-1 finishes7✅ Task-4 processed by demo-pool-thread-2 ← picked from queue after Task-2 finishes8All tasks complete. Pool terminated.Line-by-Line Explanation
1ThreadPoolExecutor executor = new ThreadPoolExecutor(2 2, // corePoolSize: always 2 threads alive3 4, // maximumPoolSize: never exceed 4 threads4 10, // keepAliveTime: idle extra threads live 10 minutes5 TimeUnit.MINUTES, // unit: keepAliveTime is in minutes6 new ArrayBlockingQueue<>(2), // workQueue: bounded, max 2 tasks waiting7 new MyCustomThreadFactory(), // threadFactory: custom names, priority, daemon8 new CustomRejectionHandler() // handler: logs rejected tasks9);1executor.submit(() -> { ... });2// Submits a Runnable (lambda) as a task.3// The pool assigns it to an available thread or queues it, per the flow above.1Thread.sleep(5000);2// Simulates that each task takes 5 seconds.3// This ensures threads stay "busy" long enough for all tasks to arrive,4// demonstrating queueing and max-thread creation.1executor.shutdown();2// Stop accepting new tasks. Let existing tasks finish.3
4executor.awaitTermination(60, TimeUnit.SECONDS);5// Block the main thread for up to 60 seconds, waiting for all tasks to complete.11. Sizing a Thread Pool The Interview Question
The Interview Scenario
The interviewer asks a candidate to implement aThreadPoolExecutor. The candidate choosescorePoolSize = 2. The interviewer follows up: "Why 2? Why not 10? Why not 15? What is the reasoning behind your choice?"
This is a design question, not a memorisation question. There is no single correct number — the correct answer demonstrates that you understand the factors that govern pool sizing and can reason through them methodically.
Factors That Determine Thread Pool Size
Factor 1: CPU Cores
Why it matters: A CPU can only run as many threads in true parallel as it has cores. Additional threads are interleaved via context switching.
12 CPU Cores:2 Thread-1 and Thread-2 run truly in parallel.3 Thread-3, Thread-4... are context-switched in/out → overhead.4
564 CPU Cores:6 Up to 64 threads can run truly in parallel.7 More than 64 → context switching begins.Rule of thumb: For pure CPU-bound work, threadCount ≈ numCpuCores.
How to get CPU cores in Java:
1int cores = Runtime.getRuntime().availableProcessors();2System.out.println("Available CPU cores: " + cores);Factor 2: Task Nature CPU-Intensive vs IO-Intensive
| Task Type | Behaviour | Optimal Thread Count |
|---|---|---|
| CPU-Intensive | Thread uses CPU continuously; minimal waiting | ≈ Number of CPU cores |
| IO-Intensive | Thread spends most time waiting for IO (DB, network, disk) | Can be significantly > number of cores |
Why more threads for IO-intensive work?
When a thread is blocked waiting for a database response, the CPU is idle. The OS can context-switch another thread in. Since the "waiting" thread isn't consuming CPU, the cost of context switching is justified by keeping the CPU busy.
1IO-Intensive example (DB calls):2Thread-1: [send query]....[waiting for DB response]....[process result]3Thread-2: [send query]...[waiting]...[process result]4Thread-3: [send query].[waiting].[process]5↑ CPU stays busy because threads are waiting, not competing for CPU time.Factor 3: JVM Memory
Each thread consumes memory:
- Thread stack: Configurable via
-XssJVM flag. Default varies by OS/JVM (typically 512KB–1MB). - Program counter register: Tiny, but per-thread.
- Native thread handle: OS-allocated overhead.
Even if the CPU can handle 1000 threads, the JVM might not have enough memory to allocate stacks for them all.
Example Calculation:
1JVM Total Memory: 2,000 MB (2 GB)2 Heap: 1,000 MB3 Code Cache: 128 MB4 JVM Internal Overhead: 256 MB5 ────────────────────────────────6 Available for threads: 616 MB (approx)7
8Stack size per thread: 5 MB (1 MB stack + 4 MB other per-thread data)9
10Max threads from memory: 616 / 5 ≈ 123 threadsFactor 4: Memory Required Per Request
One often-overlooked factor: how much heap memory does each concurrent request consume?
1Example: Each request loads 10 MB of data into heap (DB results, object graphs, etc.)2
3If 100 threads handle 100 concurrent requests:4 Memory consumed: 100 × 10 MB = 1,000 MB = 1 GB of heap5
6If your heap is only 1 GB, you'll get OutOfMemoryError.7
8Safe concurrent threads: use ~60-70% of heap9 700 MB available for requests / 10 MB per request = 70 threads maximum12. Thread Pool Sizing Formula
The Formula
A widely cited formula (from Brian Goetz's Java Concurrency in Practice) for estimating optimal thread count:
1Number of Threads = Number of CPU Cores × (1 + Wait Time / Processing Time)Where:
- Wait Time = time a thread spends waiting (IO, sleep, blocking)
- Processing Time = time a thread actively uses the CPU
Interpretation
| Scenario | Wait/Processing Ratio | Formula Result | Meaning |
|---|---|---|---|
| Pure CPU-bound | ≈ 0 | cores × 1 = cores | Threads = cores |
| Balanced (equal wait & work) | 1 | cores × 2 | 2× cores |
| Heavy IO (10× wait vs work) | 10 | cores × 11 | 11× cores |
Example Calculation
1Assumptions:2 CPU cores: 643 Request wait: 50 ms (IO wait — DB call, network, etc.)4 Processing time: 100 ms (actual CPU work)5
6Formula:7 Threads = 64 × (1 + 50/100)8 = 64 × 1.59 = 96 threads10
11→ Approximately 96 threads to keep 64 cores maximally utilised.13. Memory-Based Sizing
Step-by-Step Memory Analysis
◆ Step 1: Determine Available JVM Memory for Threads
1JVM Total Allocation (e.g., -Xmx2g): 2,000 MB2 Minus Heap (-Xmx1g): - 1,000 MB3 Minus Code Cache (-XX:ReservedCodeCacheSize): - 128 MB4 Minus JVM Internal Overhead (estimate): - 256 MB5 ─────────────────────────────────────────────────────────6 Memory available for thread stacks: 616 MB◆ Step 2: Determine Per-Thread Memory Cost
1Per-thread cost:2 Thread stack (default ~512KB, often configured to 1MB): ~1 MB3 PC register + native handle + other: ~4 MB4 Total per thread: ~5 MB◆ Step 3: Maximum Threads from Memory
1Max threads = Available Memory / Per-Thread Cost2 = 616 MB / 5 MB3 ≈ 123 threads◆ Step 4: Check Heap Headroom Per Request
1Heap size: 1,000 MB2Target usage (60% of heap for tasks): 600 MB3Memory consumed per active request: 10 MB4
5Safe concurrent threads from heap = 600 MB / 10 MB = 60 threads◆ Step 5: Reconcile All Constraints
1Formula-based estimate: ~96 threads (CPU utilisation)2Memory-based estimate: ~123 threads (stack space)3Heap-per-request estimate: ~60 threads (heap safety)4
5→ The most restrictive constraint wins: ~60 threads6
7Suggested configuration:8 corePoolSize = 50–60 (handles typical load)9 maximumPoolSize = 60–70 (handles peak with small buffer)◆ Step 6: Load Test and Iterate
No formula replaces empirical testing. After setting initial values:
- Run load tests simulating production traffic.
- Monitor with profiling tools (JVisualVM, JProfiler, Java Flight Recorder).
- Watch for: high context switching, GC pressure, thread pool rejection rates, latency percentiles.
- Adjust
corePoolSizeandmaximumPoolSizebased on observations. - Repeat.
Summary: Interview Answer Framework
When asked "Why did you choose X as your core pool size?", structure your answer:
- CPU Cores: "First I checked how many CPU cores the server has — let's say 64."
- Task Nature: "The tasks are IO-intensive (DB calls), so threads will spend significant time waiting. I used the formula:
threads = cores × (1 + waitTime/processTime)." - Formula Result: "That gave me approximately 96 threads."
- Memory Check: "But I also checked available JVM memory. With 2 GB total, after subtracting heap, code cache, and overhead, I estimated ~616 MB for thread stacks. At 5 MB per thread, that's ~123 max threads from memory alone."
- Heap Per Request: "Each request loads ~10 MB into heap. With 1 GB heap and 60% target utilisation, that allows ~60 concurrent requests safely."
- Conclusion: "So I set
corePoolSize = 50andmaximumPoolSize = 70, then ran load tests to validate and fine-tune."
14. Common Mistakes
Mistake 1: Using Unbounded Queue Without Thinking
1// ❌ WRONG — queue can grow without limit, causing OutOfMemoryError2new ThreadPoolExecutor(2, 4, 10, TimeUnit.MINUTES,3 new LinkedBlockingQueue<>()); // no capacity argument!4
5// ✅ CORRECT — bounded queue with known maximum6new ThreadPoolExecutor(2, 4, 10, TimeUnit.MINUTES,7 new ArrayBlockingQueue<>(100));Executors.newFixedThreadPool(n) and Executors.newSingleThreadExecutor() use LinkedBlockingQueue with no bound internally. This is a well-known pitfall in production systems.Mistake 2: Ignoring `allowCoreThreadTimeOut`
1// ❌ Misunderstanding: setting keepAliveTime but not enabling it for core threads2executor.setKeepAliveTime(5, TimeUnit.MINUTES);3// Core threads will STILL live forever unless:4executor.allowCoreThreadTimeOut(true); // ← this is REQUIREDMistake 3: Setting maximumPoolSize Without a Bounded Queue
1// ❌ WRONG — with unbounded queue, maximumPoolSize is NEVER triggered2new ThreadPoolExecutor(3 2, 100, 10, TimeUnit.MINUTES,4 new LinkedBlockingQueue<>() // never fills → maxPoolSize never applies5);6// In practice, this behaves like a fixed pool of 2 threads with unlimited queue.Mistake 4: Not Calling `shutdown()`
1// ❌ WRONG — executor and its core threads live forever, preventing JVM exit2ThreadPoolExecutor executor = new ThreadPoolExecutor(...);3// ... submit tasks ...4// ← forgot to call executor.shutdown()Non-daemon threads in the pool prevent the JVM from exiting. Always call shutdown() (or shutdownNow()) in a finally block or use try-with-resources patterns.
Mistake 5: Using Default AbortPolicy Without Try-Catch
1// ❌ WRONG — unhandled RejectedExecutionException will crash the submitting thread2executor.submit(task); // if pool is full, throws RejectedExecutionException3
4// ✅ CORRECT — catch rejection5try {6 executor.submit(task);7} catch (RejectedExecutionException e) {8 log.error("Task rejected — pool is at capacity", e);9}Mistake 6: Setting `corePoolSize` Arbitrarily
1// ❌ WRONG — no reasoning2int corePoolSize = 10; // why 10? no idea3
4// ✅ CORRECT — derived from CPU cores and task nature5int cores = Runtime.getRuntime().availableProcessors(); // e.g., 86double waitRatio = 2.0; // IO-intensive: wait 2× longer than processing7int corePoolSize = (int)(cores * (1 + waitRatio)); // 8 × 3 = 2415. Best Practices
1. Always Use Bounded Queues in Production
1new ArrayBlockingQueue<>(500) // choose capacity based on load analysis2. Name Your Threads
1ThreadFactory factory = r -> {2 Thread t = new Thread(r, "payment-processor-" + counter.incrementAndGet());3 t.setDaemon(false);4 return t;5};3. Always Shut Down the Pool
1Runtime.getRuntime().addShutdownHook(new Thread(() -> {2 executor.shutdown();3 try {4 if (!executor.awaitTermination(30, TimeUnit.SECONDS)) {5 executor.shutdownNow();6 }7 } catch (InterruptedException e) {8 executor.shutdownNow();9 }10}));4. Log Rejections Never Discard Silently
1// Log rejection with full context2class LoggingRejectionHandler implements RejectedExecutionHandler {3 public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {4 log.error("Task rejected. Pool size: {}, Queue size: {}, Task: {}",5 executor.getPoolSize(),6 executor.getQueue().size(),7 r);8 // Optional: push to retry queue, dead-letter queue, etc.9 }10}5. Monitor Your Pool
1// Expose these metrics via JMX, Micrometer, or logging2executor.getPoolSize(); // current active threads3executor.getActiveCount(); // threads currently executing tasks4executor.getQueue().size(); // tasks waiting in queue5executor.getCompletedTaskCount(); // total tasks completed since creation6executor.getTaskCount(); // total tasks submitted6. Prefer Direct Configuration Over `Executors` Factory Methods
1// Avoid — hides important configuration decisions2ExecutorService service = Executors.newFixedThreadPool(10);3
4// Prefer — explicit, tunable, production-ready5ThreadPoolExecutor executor = new ThreadPoolExecutor(6 10, 20, 60, TimeUnit.SECONDS,7 new ArrayBlockingQueue<>(200),8 new NamedThreadFactory("order-processor"),9 new LoggingRejectionHandler()10);16. Interview Notes
Commonly Asked Questions
Q1: What is a thread pool and why is it used?
A thread pool is a collection of pre-created, reusable worker threads. It avoids the overhead of creating and destroying threads for each task, reduces context switching by capping thread count, and abstracts thread lifecycle management.
Q2: Explain the parameters of ThreadPoolExecutor.
Walk through:corePoolSize,maximumPoolSize,keepAliveTime,unit,workQueue,threadFactory,handler. Explain the execution flow (core → queue → max → reject).
Q3: What is the difference between corePoolSize and maximumPoolSize?
corePoolSize= minimum threads always kept alive.maximumPoolSize= absolute upper limit, only reached when the queue is full. The pool never creates beyond-core threads until the queue is exhausted.
Q4: What happens when both the pool and queue are full?
TheRejectedExecutionHandleris invoked. Default isAbortPolicy(throwsRejectedExecutionException). Other options:DiscardPolicy,CallerRunsPolicy,DiscardOldestPolicy.
Q5: Why does the executor fill the queue before creating new threads?
Design philosophy:corePoolSizeshould handle average load. Queue buffers bursts without creating expensive threads. Extra threads are only created for severe bursts when the queue overflows, avoiding unnecessary thread proliferation under normal conditions.
Q6: How would you size a thread pool?
Consider: (1) CPU cores, (2) task nature (CPU-bound vs IO-bound), (3) available JVM/heap memory, (4) memory consumed per request. Use the formulathreads = cores × (1 + wait/process), then validate against memory constraints, then load-test and iterate.
Q7: What is CallerRunsPolicy and when would you use it?
The rejected task is executed in the thread that submitted it (e.g., the main/request-handling thread). This creates natural back-pressure — the submitter is slowed down while it executes the task, giving the pool time to catch up. Good for systems where task loss is unacceptable and you want organic throttling.
Q8: What is allowCoreThreadTimeOut?
A setter that, when set totrue, makes core threads (not just extra threads) subject tokeepAliveTimetermination when idle. By default, core threads never terminate.
Q9: What is the difference between shutdown() and shutdownNow()?
shutdown(): graceful — no new tasks, existing tasks finish normally.shutdownNow(): forceful — no new tasks, attempts to interrupt running tasks, returns list of unstarted queued tasks.
Q10: What is context switching and how does a thread pool help?
Context switching is when the CPU saves the state of one thread and loads another. It consumes CPU time without doing useful work. Thread pools cap thread count, reducing context switching compared to creating an unbounded number of threads.
Tricky Points to Remember
maximumPoolSizeonly activates after the queue is full, not whencorePoolSizeis exhausted.Executors.newFixedThreadPool(n)uses an unboundedLinkedBlockingQueue—maximumPoolSizeis effectively irrelevant.- Setting
keepAliveTimewithoutallowCoreThreadTimeOut(true)has no effect on core threads. shutdownNow()cannot guarantee threads are stopped — it sets interrupt flags, but threads must cooperate by checkingThread.currentThread().isInterrupted().
17. Practice Questions
Easy
- What is the purpose of a thread pool?
- What is
corePoolSize? How is it different frommaximumPoolSize? - What happens when you submit a task and a core thread is available?
- Name the four built-in rejection policies in Java.
- What does
executor.shutdown()do?
Medium
- You have a
ThreadPoolExecutorwithcorePoolSize=2,maximumPoolSize=4, queue capacity=3. You submit 9 tasks simultaneously. Describe exactly what happens to each task. - What is
CallerRunsPolicy? When would you prefer it overAbortPolicy? - What is the difference between
shutdown()andshutdownNow()? - Why does the pool fill the queue before creating threads beyond
corePoolSize? - How would you implement a thread pool that cleans up idle core threads?
Hard
- You are designing a thread pool for a microservice that makes DB calls. The server has 16 CPU cores. Each request waits ~200ms for DB and spends ~50ms processing. The JVM has 4 GB, with 2 GB heap, and each request consumes ~20 MB of heap. Derive appropriate
corePoolSizeandmaximumPoolSize.
- Explain why
Executors.newFixedThreadPool(100)can causeOutOfMemoryErrorunder heavy load.
- You observe that your thread pool is rejecting tasks frequently. Walk through a systematic approach to diagnose and fix the issue.
- Implement a thread pool that retries rejected tasks up to 3 times with exponential back-off.
- Compare
ForkJoinPoolwithThreadPoolExecutor. When would you choose one over the other?
18. Summary
1┌─────────────────────────────────────────────────────────────────┐2│ THREAD POOL — KEY POINTS │3├─────────────────────────────────────────────────────────────────┤4│ WHAT Collection of reusable worker threads │5│ WHY Saves thread creation time, manages lifecycle, │6│ controls concurrency & context switching │7│ PACKAGE java.util.concurrent │8│ KEY CLASS ThreadPoolExecutor │9├─────────────────────────────────────────────────────────────────┤10│ EXECUTION FLOW │11│ 1. Free core thread? → assign immediately │12│ 2. Queue not full? → add to queue │13│ 3. Under max threads? → create new thread │14│ 4. Otherwise? → invoke RejectedExecutionHandler │15├─────────────────────────────────────────────────────────────────┤16│ KEY PARAMETERS │17│ corePoolSize Minimum always-alive threads │18│ maximumPoolSize Absolute upper thread limit │19│ keepAliveTime+unit Idle (non-core) thread TTL │20│ workQueue Bounded or unbounded task buffer │21│ threadFactory Custom thread name, priority, daemon │22│ handler Rejection policy │23├─────────────────────────────────────────────────────────────────┤24│ LIFECYCLE: RUNNING → SHUTDOWN → TIDYING → TERMINATED │25│ shutdown() Graceful — drain queue, then terminate │26│ shutdownNow() Forceful — interrupt threads, clear queue │27├─────────────────────────────────────────────────────────────────┤28│ REJECTION POLICIES │29│ AbortPolicy Throw exception (default) │30│ DiscardPolicy Silently drop │31│ CallerRunsPolicy Run in caller's thread (back-pressure) │32│ DiscardOldestPolicy Remove oldest queued task, retry new one │33├─────────────────────────────────────────────────────────────────┤34│ SIZING FACTORS │35│ CPU cores, task nature (CPU vs IO), JVM memory, │36│ heap per request, concurrency requirements │37│ Formula: threads = cores × (1 + waitTime/processTime) │38│ Always validate with load testing │39└─────────────────────────────────────────────────────────────────┘Quick-Revision Bullets
- A thread pool reuses threads — avoids creation/destruction overhead per task.
corePoolSizethreads are always alive, even idle (unlessallowCoreThreadTimeOut(true)).- Task submission order: core threads → queue → extra threads (up to max) → reject.
- Extra threads (above core) are terminated after
keepAliveTimewhen idle. - Always use a bounded queue (
ArrayBlockingQueue) in production. shutdown()= graceful;shutdownNow()= forceful.- Thread pool sizing must consider CPU cores + task nature + JVM memory + heap per request.
- The formula
threads = cores × (1 + wait/process)is a starting point, not a final answer. - Load testing and monitoring are mandatory for production thread pool tuning.
End of Java Thread Pool Study Guide
Mastery check
How well can you recall this?
Finished this lesson?