All topics
library
advanced

Fork/Join Framework

Divide computational tasks into subtasks recursively and process them in parallel with work-stealing.

The Fork/Join framework (Java 7) is designed for divide-and-conquer parallelism: break a task into subtasks, process them in parallel, and combine results. It uses a ForkJoinPool with work-stealing scheduling.

Fork/Join = a team of chefs preparing a banquet. The head chef (main task) divides the menu (fork). Each chef works on their dishes. If one finishes early, they help others (work stealing). Finally, all dishes are combined (join).

Key Concepts

1
Key classes: - ForkJoinPool: the thread pool. Uses work-stealing: idle threads steal tasks from busy threads' queues. The common pool (ForkJoinPool.commonPool()) is shared and used by parallel streams. - RecursiveTask<V>: a task that returns a result. Override compute(). - RecursiveAction: a task with no result. Override compute().
2
Pattern: 1. Check if the task is small enough to compute directly (base case) 2. If not, split into subtasks (fork) 3. Wait for subtasks to complete (join) 4. Combine results
3
Work-stealing: each thread has a deque of tasks. A thread processes from one end; stealing threads take from the other end. This balances load automatically — no central queue bottleneck.
4
Parallel streams use Fork/Join internally: list.parallelStream().reduce() creates Fork/Join tasks under the hood.
5
Threshold tuning: setting the right base-case threshold is critical. Too small = excessive task creation overhead. Too large = poor parallelism. Start with n/availableProcessors and benchmark.