Executors & ForkJoinPool
ForkJoinPool, RecursiveTask, work-stealing algorithm, parallel array operations
- Implement divide-and-conquer algorithms with RecursiveTask
- Understand ForkJoinPool work-stealing for CPU-bound tasks
- Compare ForkJoinPool with standard ExecutorService
A comprehensive study guide covering theExecutorsfactory class, all standard thread pool types, the Fork-Join framework, Work-Stealing pools, and recursive task decomposition.
Table of Contents
- Background: Custom Thread Pool Executor
- The
ExecutorsUtility Class - Fixed Thread Pool Executor
- Cached Thread Pool Executor
- Single Thread Executor
- Work-Stealing Pool Executor & Fork-Join Pool
- How Work-Stealing Works — Deep Dive
- RecursiveTask and RecursiveAction
- Fork and Join — The Core Mechanism
- Complete Code Example: Parallel Sum
- Submission Queue vs Work-Stealing Queue
- Thread Count in Fork-Join Pool
- Comparison Table of All Pool Types
- Memory & JVM Behavior
- Interview Notes
- Common Mistakes
- Best Practices
- Practice Questions
- Summary
1. Background: Custom Thread Pool Executor
Overview
Before the Executors utility class, developers created thread pools manually using ThreadPoolExecutor — often called a custom thread pool executor. This gave full control over every configuration parameter.
Syntax
1import java.util.concurrent.*;2
3ThreadPoolExecutor executor = new ThreadPoolExecutor(4 corePoolSize, // minimum number of threads always alive5 maximumPoolSize, // maximum threads allowed6 keepAliveTime, // idle time before extra threads die7 TimeUnit.SECONDS, // unit of keepAliveTime8 new LinkedBlockingQueue<>(queueCapacity) // work queue9);Why It Existed
When you need precise control — e.g. a specific rejection policy, a specific queue type, or different min/max pool sizes — the custom ThreadPoolExecutor is the right tool. However, for common use cases, this is verbose. The Executors class provides factory methods that cover the most frequent patterns with a single method call.
2. The `Executors` Utility Class
Overview
Executors is a utility class located in the java.util.concurrent package. It provides a collection of static factory methods that create pre-configured ThreadPoolExecutor (or ForkJoinPool) instances for common use cases.
Package
1import java.util.concurrent.Executors;2import java.util.concurrent.ExecutorService;Why This Class Exists
| Problem | Solution |
|---|---|
Creating a ThreadPoolExecutor manually is verbose and error-prone | Executors provides one-liner factory methods |
| Common configurations (fixed, cached, single) are reinvented repeatedly | Factory methods encode best-practice configurations |
| Hard to choose the right queue type and keep-alive settings | Factory methods bundle correct defaults |
Available Factory Methods (covered in this guide)
| Method | Returns |
|---|---|
Executors.newFixedThreadPool(n) | Fixed-size ThreadPoolExecutor |
Executors.newCachedThreadPool() | Dynamically-scaling ThreadPoolExecutor |
Executors.newSingleThreadExecutor() | Single-thread ThreadPoolExecutor |
Executors.newWorkStealingPool() | ForkJoinPool with work-stealing |
Executors.newWorkStealingPool(n) | ForkJoinPool with explicit parallelism |
3. Fixed Thread Pool Executor
Overview
Creates a thread pool with a fixed, unchanging number of threads. The minimum pool size and the maximum pool size are identical — whatever number you supply.
Definition
A ThreadPoolExecutor where corePoolSize == maximumPoolSize, backed by an unbounded LinkedBlockingQueue.
Syntax
1ExecutorService executor = Executors.newFixedThreadPool(5);Configuration Properties
| Property | Value |
|---|---|
| Core Pool Size (minimum) | n (the number you provide) |
| Maximum Pool Size | n (same as core — fixed!) |
| Queue Type | LinkedBlockingQueue (unbounded) |
| Queue Capacity | Unbounded (grows as needed, limited only by memory) |
| Thread Keep-Alive When Idle | Threads stay alive forever — never terminated even if idle |
Code Example
1import java.util.concurrent.ExecutorService;2import java.util.concurrent.Executors;3
4public class FixedThreadPoolDemo {5 public static void main(String[] args) {6 // Create a fixed pool of 5 threads7 ExecutorService executor = Executors.newFixedThreadPool(5);8
9 for (int i = 1; i <= 10; i++) {10 final int taskId = i;11 executor.submit(() -> {12 System.out.println("Task " + taskId + " running on: "13 + Thread.currentThread().getName());14 try {15 Thread.sleep(1000); // simulate work16 } catch (InterruptedException e) {17 Thread.currentThread().interrupt();18 }19 });20 }21
22 executor.shutdown();23 }24}Expected Output (approximate)
1Task 1 running on: pool-1-thread-12Task 2 running on: pool-1-thread-23Task 3 running on: pool-1-thread-34Task 4 running on: pool-1-thread-45Task 5 running on: pool-1-thread-56Task 6 running on: pool-1-thread-1 ← thread reused after Task 1 finishes7Task 7 running on: pool-1-thread-28...Line-by-Line Explanation
| Line | Explanation |
|---|---|
Executors.newFixedThreadPool(5) | Creates exactly 5 threads. Min = Max = 5. |
executor.submit(...) | Submits a Runnable task. If all 5 threads are busy, task waits in the unbounded queue. |
executor.shutdown() | Stops accepting new tasks; completes pending ones before terminating. |
When to Use
- You know exactly how many concurrent tasks you need.
- You want a predictable, stable resource footprint.
- Example: a server handling exactly N parallel database connections.
Disadvantage
n threads. Tasks pile up in the unbounded queue. Under extreme load this can cause memory exhaustion because the queue grows without limit.Equivalent Custom Configuration
1// This is what newFixedThreadPool(5) does internally:2ThreadPoolExecutor equivalent = new ThreadPoolExecutor(3 5, // corePoolSize4 5, // maximumPoolSize (same = fixed)5 0L, // keepAliveTime (irrelevant, core threads never die)6 TimeUnit.MILLISECONDS,7 new LinkedBlockingQueue<>() // unbounded queue8);Flowchart
4. Cached Thread Pool Executor
Overview
Creates a thread pool that dynamically creates new threads on demand and terminates idle threads after 60 seconds. There is no fixed upper limit on threads (up to Integer.MAX_VALUE).
Definition
A ThreadPoolExecutor with corePoolSize = 0, maximumPoolSize = Integer.MAX_VALUE, a SynchronousQueue (which has zero capacity — tasks are handed off directly to a thread or a new thread is created), and a keep-alive time of 60 seconds.
Syntax
1ExecutorService executor = Executors.newCachedThreadPool();Configuration Properties
| Property | Value |
|---|---|
| Core Pool Size (minimum) | 0 — no threads kept permanently |
| Maximum Pool Size | Integer.MAX_VALUE (~2.1 billion) |
| Queue Type | SynchronousQueue (capacity = 0; a direct hand-off queue) |
| Queue Capacity | Zero — tasks are never queued; a thread is always created |
| Thread Keep-Alive When Idle | 60 seconds — idle threads are terminated after 60 s |
Code Example
1import java.util.concurrent.ExecutorService;2import java.util.concurrent.Executors;3
4public class CachedThreadPoolDemo {5 public static void main(String[] args) throws InterruptedException {6 ExecutorService executor = Executors.newCachedThreadPool();7
8 // Simulate a burst of 10 short-lived tasks9 for (int i = 1; i <= 10; i++) {10 final int taskId = i;11 executor.submit(() -> {12 System.out.println("Task " + taskId + " on: "13 + Thread.currentThread().getName());14 try {15 Thread.sleep(200); // short task16 } catch (InterruptedException e) {17 Thread.currentThread().interrupt();18 }19 });20 }21
22 // After tasks complete, threads sit idle for 60 seconds then die23 executor.shutdown();24 }25}Expected Output
1Task 1 on: pool-1-thread-12Task 2 on: pool-1-thread-23Task 3 on: pool-1-thread-34...5Task 10 on: pool-1-thread-10All 10 threads are created simultaneously because all 10 tasks arrive before any thread completes.
When to Use
- Burst of short-lived tasks — many tasks arrive suddenly but each completes quickly.
- Workloads that are spiky and unpredictable in size.
Disadvantage
OutOfMemoryError.
Rule: Only use newCachedThreadPool() for short-lived tasks.Equivalent Custom Configuration
1ThreadPoolExecutor equivalent = new ThreadPoolExecutor(2 0, // corePoolSize: no permanent threads3 Integer.MAX_VALUE, // maximumPoolSize: unlimited4 60L, // keepAliveTime: 60 seconds5 TimeUnit.SECONDS,6 new SynchronousQueue<>() // zero-capacity direct handoff7);Flowchart
5. Single Thread Executor
Overview
Creates a thread pool with exactly one worker thread. All submitted tasks are executed sequentially, one at a time, in submission order.
Definition
A ThreadPoolExecutor with both corePoolSize and maximumPoolSize set to 1, backed by an unbounded LinkedBlockingQueue.
Syntax
1ExecutorService executor = Executors.newSingleThreadExecutor();Configuration Properties
| Property | Value |
|---|---|
| Core Pool Size (minimum) | 1 |
| Maximum Pool Size | 1 |
| Queue Type | LinkedBlockingQueue (unbounded) |
| Queue Capacity | Unbounded |
| Thread Keep-Alive When Idle | Thread stays alive forever |
Code Example
1import java.util.concurrent.ExecutorService;2import java.util.concurrent.Executors;3
4public class SingleThreadExecutorDemo {5 public static void main(String[] args) {6 ExecutorService executor = Executors.newSingleThreadExecutor();7
8 for (int i = 1; i <= 5; i++) {9 final int taskId = i;10 executor.submit(() -> {11 System.out.println("Task " + taskId + " on: "12 + Thread.currentThread().getName());13 try {14 Thread.sleep(500);15 } catch (InterruptedException e) {16 Thread.currentThread().interrupt();17 }18 });19 }20
21 executor.shutdown();22 }23}Expected Output
1Task 1 on: pool-1-thread-12Task 2 on: pool-1-thread-13Task 3 on: pool-1-thread-14Task 4 on: pool-1-thread-15Task 5 on: pool-1-thread-1Always the same thread, always in order.
When to Use
- Tasks must be processed strictly sequentially (ordering matters).
- You need to serialize access to a shared resource from multiple callers.
- Example: writing log entries in order, processing a queue of database writes sequentially.
Disadvantage
6. Work-Stealing Pool Executor & Fork-Join Pool
Overview
Executors.newWorkStealingPool() creates a ForkJoinPool internally — a specialized thread pool designed for divide-and-conquer parallelism. It uses a technique called work stealing to maximize CPU utilization.
The Core Idea: Fork-Join
The Fork-Join framework operates on a simple principle:
- Fork — Split a large task into smaller subtasks.
- Execute — Each subtask runs (possibly splitting further — recursively).
- Join — Wait for all subtasks to finish, then combine their results.
Why Fork-Join Exists
In a standard thread pool, a single large task is handled by one thread from start to finish. If that task could logically be split into independent sub-computations, the other idle threads sit unused. The Fork-Join framework solves this by enabling task decomposition and distributing the sub-pieces across all available threads.
Real-World Analogy
Imagine computing the sum of 1 billion numbers:
- Old way: One accountant adds all numbers one by one.
- Fork-Join way: Divide the list into chunks. Give each chunk to a different accountant. Each accountant sums their chunk. Collect all partial sums and add them together.
More accountants working in parallel → faster result.
7. How Work-Stealing Works Deep Dive
The Problem With Standard Thread Pools
In a standard ThreadPoolExecutor:
1Thread Pool: [Thread-1] [Thread-2]2 ↑ ↑3 Shared Queue: [Task3] [Task4] [Task5]- All threads share a single queue.
- Threads pick from the front of the queue.
- If a thread is busy, it cannot help another busy thread.
- There is no mechanism for one thread to take over part of another thread's work.
The Work-Stealing Innovation
Fork-Join pools introduce per-thread work-stealing deques (double-ended queues):
1[Thread-1] ←→ [Its own Deque: SubTask-A | SubTask-B]2[Thread-2] ←→ [Its own Deque: SubTask-C | SubTask-D]3 ↑4 Global Submission Queue: [Task3] [Task4]Each thread has its own private deque. This is the work-stealing queue.
Detailed Step-by-Step Flow
Let's walk through a complete scenario:
◆ Initial State
1Thread Pool: Thread-1 (free), Thread-2 (free)2Submission Queue: []3Thread-1's Work-Stealing Deque: []4Thread-2's Work-Stealing Deque: []◆ Step 1 Task-1 arrives (a simple task)
1Task-1 submitted → Thread-1 picks it up → Thread-1: BUSY with Task-1◆ Step 2 Task-2 arrives (a RecursiveTask can be split)
1Task-2 submitted → Thread-2 picks it up → Thread-2: BUSY with Task-2◆ Step 3 Task-3 arrives (both threads busy)
1Task-3 submitted → Both threads busy → Task-3 goes into Submission Queue2Submission Queue: [Task-3]◆ Step 4 Thread-2 forks Task-2 into SubTask-2a and SubTask-2b
1Thread-2 splits Task-2:2 Thread-2 begins working on SubTask-2a (from the FRONT of its deque)3 SubTask-2b pushed to Thread-2's work-stealing deque4
5Thread-2's Deque: [SubTask-2b] ← can be stolen from the BACK6Thread-2: Working on SubTask-2a◆ Step 5 Thread-1 completes Task-1, looks for work
Priority order for a free thread:
| Priority | Check | Action |
|---|---|---|
| 1st | Own work-stealing deque | Take from front |
| 2nd | Global submission queue | Take from front |
| 3rd | Other threads' deques | Steal from the back |
1Thread-1 finishes Task-1.2→ Check own deque: empty3→ Check submission queue: Task-3 is there!4→ Thread-1 picks Task-3 from submission queue5Thread-1: BUSY with Task-3◆ Step 6 Thread-1 completes Task-3, still SubTask-2b is pending
1Thread-1 finishes Task-3.2→ Check own deque: empty3→ Check submission queue: empty4→ Check other threads' deques: Thread-2 has SubTask-2b in its deque!5→ Thread-1 STEALS SubTask-2b from the BACK of Thread-2's deque6
7Thread-2's Deque: [] (SubTask-2b stolen)8Thread-1: Now working on SubTask-2bThis is the work-stealing act. Thread-1 steals work from Thread-2's queue to keep itself busy.
Why Steal from the BACK?
Work-Stealing Flow Diagram
8. RecursiveTask and RecursiveAction
Overview
To use the Fork-Join framework, your task class must extend either RecursiveTask or RecursiveAction. Both live in java.util.concurrent.
The Difference
RecursiveTask | RecursiveAction | |
|---|---|---|
| Return value | Yes — generic type V | No — void |
compute() signature | protected V compute() | protected void compute() |
| Use case | Task that produces a result (e.g. sum, count) | Task that performs side effects (e.g. sorting in place, file processing) |
Class Hierarchy
The `compute()` Method
Both classes require you to override the compute() method. This is where you:
- Check whether the task is small enough to solve directly (the base case).
- If not, split the task into subtasks, fork them, and join their results.
Syntax RecursiveTask
1class MyTask extends RecursiveTask<Integer> {2 @Override3 protected Integer compute() {4 if (/* base case: task is small enough */) {5 return directComputation();6 } else {7 MyTask leftTask = new MyTask(/* left half */);8 MyTask rightTask = new MyTask(/* right half */);9 leftTask.fork(); // schedule leftTask for async execution10 int rightResult = rightTask.compute(); // execute right inline11 int leftResult = leftTask.join(); // wait for leftTask result12 return leftResult + rightResult;13 }14 }15}Syntax RecursiveAction
1class MyAction extends RecursiveAction {2 @Override3 protected void compute() {4 if (/* base case */) {5 performDirectWork();6 } else {7 MyAction leftAction = new MyAction(/* left half */);8 MyAction rightAction = new MyAction(/* right half */);9 invokeAll(leftAction, rightAction); // fork both and wait10 }11 }12}9. Fork and Join The Core Mechanism
`fork()`
1leftTask.fork();What it does:
- Schedules the task for asynchronous execution in the Fork-Join pool.
- The current thread does not block.
- The forked task is placed into the current thread's work-stealing deque (pushed to the front).
- Other free threads may steal it from the back of that deque.
Analogy: You hand off a sub-problem to a colleague and immediately start working on your own part without waiting.
`join()`
1int result = leftTask.join();What it does:
- Blocks the calling thread until the task completes.
- Returns the result (for
RecursiveTask). - While waiting, the calling thread can execute other tasks from its deque (it does not simply sit idle — this is a key performance feature called helping).
Analogy: You've finished your part. Now you wait for your colleague's result so you can combine them.
`invoke()`
1int result = task.invoke();Equivalent to fork() followed immediately by join(). Executes the task and returns the result. Used at the top level.
`invokeAll(task1, task2)`
Forks both tasks and waits for both to complete. Convenient shorthand.
Sequence Diagram
10. Complete Code Example: Parallel Sum
Problem
Compute the sum of all integers from start to end (inclusive) using Fork-Join parallelism.
Strategy
- Base case: If the range has 4 or fewer elements, sum them directly (no further splitting).
- Recursive case: Split the range in half, create two subtasks, fork one, compute the other, join and sum.
Code
1import java.util.concurrent.ForkJoinPool;2import java.util.concurrent.RecursiveTask;3
4// Task class: extends RecursiveTask<Integer> because it returns an Integer5class ComputeSumTask extends RecursiveTask<Integer> {6
7 private final int start;8 private final int end;9
10 // Constructor: sets the range this task will sum11 public ComputeSumTask(int start, int end) {12 this.start = start;13 this.end = end;14 }15
16 @Override17 protected Integer compute() {18 // Base case: range is small enough to compute directly19 if (end - start <= 4) {20 int sum = 0;21 for (int i = start; i <= end; i++) {22 sum += i;23 }24 System.out.println(Thread.currentThread().getName()25 + " summing [" + start + ", " + end + "] = " + sum);26 return sum;27 }28
29 // Recursive case: split the range30 int mid = start + (end - start) / 2;31
32 ComputeSumTask leftTask = new ComputeSumTask(start, mid);33 ComputeSumTask rightTask = new ComputeSumTask(mid + 1, end);34
35 // Fork the left task → pushes it to this thread's work-stealing deque36 leftTask.fork();37
38 // Compute the right task on the current thread (inline)39 int rightResult = rightTask.compute();40
41 // Join: wait for left task to finish, get its result42 int leftResult = leftTask.join();43
44 return leftResult + rightResult;45 }46}47
48public class ForkJoinDemo {49 public static void main(String[] args) {50 // Method 1: Using ForkJoinPool.commonPool()51 ForkJoinPool pool = ForkJoinPool.commonPool();52
53 ComputeSumTask task = new ComputeSumTask(1, 16);54
55 int result = pool.invoke(task); // submit and wait for result56
57 System.out.println("Total Sum (1 to 16) = " + result);58 // Expected: 1+2+...+16 = 13659
60 // Method 2: Using newWorkStealingPool (equivalent)61 // ExecutorService wsPool = Executors.newWorkStealingPool();62 // Future<Integer> future = wsPool.submit(task);63 // int r = future.get();64 }65}Expected Output (thread names vary)
1ForkJoinPool.commonPool-worker-1 summing [1, 4] = 102ForkJoinPool.commonPool-worker-2 summing [5, 8] = 263ForkJoinPool.commonPool-worker-3 summing [9, 12] = 424ForkJoinPool.commonPool-worker-4 summing [13, 16] = 585Total Sum (1 to 16) = 136Step-by-Step Execution
1Task(1,16)2 → mid = 83 → leftTask = Task(1,8) → forked (goes to work-stealing deque)4 → rightTask = Task(9,16) → computed inline5
6Task(9,16)7 → mid = 128 → leftTask = Task(9,12) → forked9 → rightTask = Task(13,16) → computed inline10
11Task(13,16): end-start = 3 ≤ 4 → sum directly = 5812
13Task(9,12): end-start = 3 ≤ 4 → sum directly = 4214 → join returns 4215 → Task(9,16) returns 42 + 58 = 10016
17Meanwhile, Task(1,8) was stolen/executed:18Task(1,8)19 → mid = 420 → leftTask = Task(1,4) → forked21 → rightTask = Task(5,8) → computed inline22
23Task(5,8): end-start = 3 ≤ 4 → sum directly = 2624Task(1,4): end-start = 3 ≤ 4 → sum directly = 1025 → Task(1,8) returns 10 + 26 = 3626
27Final join:28 leftResult = 36 (from Task(1,8))29 rightResult = 100 (from Task(9,16))30 Total = 136 ✓Task Decomposition Tree
11. Submission Queue vs Work-Stealing Queue
Two Types of Queues in Fork-Join Pool
| Property | Submission Queue | Work-Stealing Queue |
|---|---|---|
| Number | One — shared globally | One per thread |
| Type | Regular blocking queue | Deque (double-ended queue) |
| Who adds to it | External callers (submit(), invoke()) | The owning thread (fork()) |
| Who reads from it | Any free thread | Owner reads from front; others steal from back |
| Can be stolen? | No — tasks cannot be stolen from the submission queue | Yes — other threads steal from the back |
When Does a Task Go to the Submission Queue?
When you call:
1pool.submit(task);2pool.invoke(task);The task enters the submission queue. Any free thread picks it up.
When Does a Task Go to the Work-Stealing Queue?
When you call:
1subtask.fork();The subtask is pushed to the front of the current thread's work-stealing deque.
Why a Deque and Not a Simple Queue?
A deque (double-ended queue) allows:
- The owning thread to push/pop from the front (LIFO for the owner — better cache locality, works on the most recently created/smallest task first).
- Stealing threads to pop from the back (FIFO for stealers — they get the oldest, largest tasks, which is more efficient to steal because larger tasks give stealers more work per steal).
12. Thread Count in Fork-Join Pool
Default: Based on Available Processors
1// No argument — uses all available CPU cores2ExecutorService pool = Executors.newWorkStealingPool();Internally calls:
1Runtime.getRuntime().availableProcessors()| CPU Cores | Threads Created |
|---|---|
| 4 | 4 |
| 8 | 8 |
| 16 | 16 |
This is parallelism level — matching threads to cores avoids context-switching overhead.
Explicit Parallelism
1// Specify exactly how many threads you want2ExecutorService pool = Executors.newWorkStealingPool(8);Both min and max are set to the given value. The pool maintains this many threads continuously.
Accessing the Common Pool
1// The JVM-wide shared Fork-Join pool (parallelism = available CPUs)2ForkJoinPool commonPool = ForkJoinPool.commonPool();3int result = commonPool.invoke(new ComputeSumTask(1, 100));ForkJoinPool.commonPool() is a shared pool used by parallel streams and other JDK frameworks. Be mindful that blocking tasks in it can affect the entire JVM.13. Comparison Table of All Pool Types
| Feature | Fixed Thread Pool | Cached Thread Pool | Single Thread Executor | Work-Stealing Pool |
|---|---|---|---|---|
| Min Threads | n | 0 | 1 | parallelism level |
| Max Threads | n | Integer.MAX_VALUE | 1 | parallelism level |
| Queue Type | LinkedBlockingQueue (unbounded) | SynchronousQueue (capacity 0) | LinkedBlockingQueue (unbounded) | Submission Queue + per-thread deque |
| Thread Lifespan When Idle | Forever | 60 seconds then terminated | Forever | Varies |
| Task Decomposition | No | No | No | Yes (fork-join) |
| Work Stealing | No | No | No | Yes |
| Best For | Known fixed concurrency | Burst short tasks | Sequential processing | Divide-and-conquer / parallel computation |
| Worst For | Heavy variable workloads | Long-running tasks | Concurrent tasks | Tasks that cannot be subdivided |
14. Memory & JVM Behavior
Stack Memory
Each thread has its own call stack. When compute() is called recursively (or new task objects call compute()), each invocation gets a new stack frame.
For deep recursion on large tasks (e.g. summing 10 million elements with base case 1), this can cause StackOverflowError. Always use a reasonably large base-case threshold.
Heap Memory
- Task objects (
ComputeSumTaskinstances) are allocated on the heap. - Each fork creates a new object. For very fine-grained decomposition, GC pressure increases.
Method Area (Metaspace)
Class definitions for ComputeSumTask, ForkJoinPool, RecursiveTask, etc. are loaded once into the Metaspace.
Thread Memory
Each thread in the pool has:
- Its own stack (default ~512KB–1MB per thread, configurable).
- A reference to its own work-stealing deque (on the heap).
Memory Diagram
1JVM Memory2├── Heap3│ ├── Task objects (ComputeSumTask instances)4│ ├── ForkJoinPool object5│ └── Deque objects (one per thread, holding task references)6│7├── Stack (per thread)8│ ├── Thread-1 Stack: compute() frame → compute() frame → ...9│ ├── Thread-2 Stack: compute() frame → ...10│ └── Thread-N Stack: ...11│12└── Metaspace13 ├── ForkJoinPool.class14 ├── RecursiveTask.class15 └── ComputeSumTask.class15. Interview Notes
Q1: What is the difference between `ExecutorService` and `ForkJoinPool`?
ExecutorService (ThreadPoolExecutor) | ForkJoinPool |
|---|---|
| Tasks run independently | Tasks can be split into subtasks |
| Single shared queue | Submission queue + per-thread deques |
| No work stealing | Work stealing between threads |
| Good for I/O-bound tasks | Good for CPU-bound parallel tasks |
Q2: What is the purpose of the `fork()` method?
fork() submits a subtask for asynchronous parallel execution by placing it into the current thread's work-stealing deque. It does not block. Other free threads may steal and execute it.
Q3: What does `join()` do internally?
join() waits for the task to complete. If the calling thread is a Fork-Join thread, it may help execute other tasks while waiting (cooperative scheduling), rather than blocking.
Q4: What is work stealing and why is it efficient?
Work stealing allows idle threads to take tasks from the back of busy threads' deques. This maximizes CPU utilization without a central bottleneck (no single shared queue lock). The use of a deque minimizes contention because the owner works from the front and stealers take from the back.
Q5: Why does `newCachedThreadPool()` use a `SynchronousQueue`?
A SynchronousQueue has zero capacity. A task can only be inserted if a thread is immediately ready to take it. This forces the pool to create a new thread if none is available — which is the desired behavior for the cached pool.
Q6: When should you NOT use `newCachedThreadPool()`?
When tasks are long-running. If 1000 long tasks are submitted, 1000 threads are created simultaneously, leading to excessive memory consumption and CPU context-switching.
Q7: What is `ForkJoinPool.commonPool()`?
A JVM-wide singleton ForkJoinPool shared across the application. Java's parallel streams use it internally. Tasks submitted to it should be short and non-blocking to avoid starving other users of the pool.
Q8: What is the difference between `RecursiveTask` and `RecursiveAction`?
RecursiveTask returns a value (compute() returns V). RecursiveAction is void (compute() returns nothing). Use RecursiveTask when you need a result, RecursiveAction for side-effect-only operations.
Q9: Why does the work-stealing deque use the front for the owner and back for stealers?
- Owner takes from front (LIFO): More recently forked tasks are at the front. They are smaller, faster to process, and still hot in CPU cache.
- Stealers take from back (FIFO): Older tasks are at the back. They tend to be larger (less subdivided), giving the stealer more work per steal and reducing how frequently stealing needs to happen.
Q10: What is the priority order for a thread looking for work in a Fork-Join pool?
- Check its own work-stealing deque (take from front).
- Check the global submission queue.
- Steal from another thread's deque (take from back).
16. Common Mistakes
Mistake 1: Using `newCachedThreadPool()` for long-running tasks
1// ❌ WRONG: submitting slow tasks to cached pool2ExecutorService ex = Executors.newCachedThreadPool();3for (int i = 0; i < 10000; i++) {4 ex.submit(() -> {5 Thread.sleep(60000); // 1 minute task!6 });7}8// Creates 10,000 threads → OutOfMemoryError1// ✅ CORRECT: use fixed pool for known long-running tasks2ExecutorService ex = Executors.newFixedThreadPool(3 Runtime.getRuntime().availableProcessors()4);Mistake 2: Calling `compute()` recursively instead of using `fork()`
1// ❌ WRONG: directly calling compute() is just normal recursion — no parallelism2protected Integer compute() {3 leftTask.compute(); // sequential, not parallel4 rightTask.compute(); // sequential, not parallel5}1// ✅ CORRECT: fork one, compute the other inline2protected Integer compute() {3 leftTask.fork(); // async — another thread may pick this up4 int right = rightTask.compute(); // do this work on the current thread5 int left = leftTask.join(); // wait for leftTask6 return left + right;7}Mistake 3: Forgetting to call `join()`
1// ❌ WRONG: fork but never join — result is lost2leftTask.fork();3return rightTask.compute(); // leftTask result ignored!1// ✅ CORRECT: always join after fork2leftTask.fork();3int right = rightTask.compute();4int left = leftTask.join(); // collect leftTask's result5return left + right;Mistake 4: Base case too small
1// ❌ WRONG: splitting down to 1 element each2if (end - start <= 1) { return end; }Splitting to 1-element tasks creates enormous numbers of task objects and deque operations. Choose a threshold (e.g. 100–1000 elements) that balances parallelism with overhead.
Mistake 5: Blocking operations inside Fork-Join tasks
1// ❌ WRONG: blocking I/O inside a RecursiveTask2protected Integer compute() {3 String data = readFromDatabase(); // blocks the thread!4 // ...5}Fork-Join threads are designed for CPU-bound work. Blocking operations stall a precious pool thread and can cause all parallelism to seize up. For I/O-bound work, use a standard ThreadPoolExecutor.
Mistake 6: Submitting to `newFixedThreadPool()` and expecting it to grow
1ExecutorService ex = Executors.newFixedThreadPool(4);2// Submitting 1000 tasks — only 4 run at a time.3// The other 996 wait in the unbounded queue. That is by design.4// If you expected auto-scaling, use newCachedThreadPool() instead (with care).17. Best Practices
- Choose the right pool for the job:
- Known, fixed parallelism →
newFixedThreadPool(n) - Burst of short tasks →
newCachedThreadPool() - Sequential task processing →
newSingleThreadExecutor() - Divide-and-conquer CPU computation →
newWorkStealingPool()/ForkJoinPool
- Set the base case threshold carefully. Too small → too many task objects and overhead. Too large → insufficient parallelism. A common heuristic is to split until each chunk takes ~1ms to execute.
- Always shut down executors to avoid resource leaks:
1 executor.shutdown();2 executor.awaitTermination(60, TimeUnit.SECONDS);- Do not block inside Fork-Join tasks. Fork-Join excels at CPU-bound, non-blocking computation. For I/O-bound work, use a standard thread pool with a larger thread count.
- Use
ForkJoinPool.commonPool()cautiously. If your tasks block, you starve every other user of the common pool (including Java parallel streams).
- Prefer
invokeAll()for multiple independent subtasks to simplify code:
1 invokeAll(leftTask, rightTask);2 int left = leftTask.join();3 int right = rightTask.join();- Do not share mutable state between fork-join tasks without synchronization. The whole point of task decomposition is independent sub-problems — if tasks share data, you reintroduce race conditions.
18. Practice Questions
Easy
- What class provides factory methods for creating thread pools in Java?
- What is the difference between
corePoolSizeandmaximumPoolSizein anewFixedThreadPool? - How long does an idle thread survive in a cached thread pool?
- Write one line of code to create a fixed thread pool of 8 threads.
- What package contains
Executors,ForkJoinPool, andRecursiveTask?
Medium
- You have a server that handles exactly 10 simultaneous database queries. Which
Executorsfactory method would you use and why? - Explain why
newCachedThreadPool()should not be used for long-running tasks. - Describe the three-priority order in which a Fork-Join thread looks for work.
- What is the difference between the submission queue and the work-stealing queue in a Fork-Join pool?
- Rewrite the
ComputeSumTaskexample to work with an array oflongvalues instead of a range.
Hard
- Implement a parallel merge-sort using
RecursiveAction(no return value — sort the array in place). - A
ForkJoinPoolwith 4 threads is processing tasks. Thread-1, Thread-2, Thread-3, Thread-4 all pick tasks simultaneously. Thread-1's task forks into 6 subtasks. Trace exactly how the work-stealing queues change over time. - Explain why using
fork()on both subtasks (instead of fork-one, compute-one) is less efficient. What is lost? - How does
join()avoid simply blocking the calling thread? Describe the "helping" mechanism. - Compare the memory overhead of
newFixedThreadPool(100)vsnewWorkStealingPool()on a 4-core machine when processing 1000 tasks.
19. Summary
Key Bullet Points
Executorsis a utility class injava.util.concurrentwith static factory methods for common thread pool configurations.- Fixed thread pool: min = max = n; unbounded queue; threads never die; limited by fixed concurrency.
- Cached thread pool: min = 0, max = unlimited; zero-capacity
SynchronousQueue; threads die after 60s idle; for short-lived bursts only. - Single thread executor: 1 thread; sequential; no concurrency.
- Work-stealing pool internally creates a
ForkJoinPool. Its key innovation is per-thread deques and work stealing. - Fork-Join = divide a large task using
fork(), execute parts in parallel, wait withjoin(), combine results. - A free thread checks: (1) own deque → (2) submission queue → (3) steal from another thread's deque.
- Owner takes from the front of its deque; stealers take from the back — minimizing contention.
- Extend
RecursiveTaskwhen you need a return value; extendRecursiveActionfor void tasks. fork()is async (non-blocking);join()waits for completion (can help execute other tasks while waiting).ForkJoinPool.commonPool()is the JVM-wide shared pool; avoid blocking tasks in it.- Default thread count in
newWorkStealingPool()=Runtime.getRuntime().availableProcessors(). - Fork-Join is ideal for CPU-bound, non-blocking, recursively decomposable problems.
End of Chapter — Java Executors Utility Class & Fork-Join Pool
Mastery check
How well can you recall this?
Finished this lesson?