Java / Java Concurrency and Multi Threading in Java 17 and Java 21 Interview questions
How does the ForkJoinPool execute tasks?
ForkJoinPool is designed for divide-and-conquer workloads: a large task is recursively split into smaller subtasks until they're cheap enough to compute directly, then results are combined.
You express this with RecursiveTask<V> (returns a value) or RecursiveAction (no return value). Calling fork() schedules a subtask to run asynchronously on the pool, and join() waits for it and retrieves its result.
class SumTask extends RecursiveTask<Long> { protected Long compute() { if (smallEnough()) return computeDirectly(); SumTask left = new SumTask(firstHalf); SumTask right = new SumTask(secondHalf); left.fork(); // run left asynchronously long r = right.compute(); // compute right on this thread return left.join() + r; // combine } }
Under the hood, each worker thread has its own double-ended task queue and uses a work-stealing scheduler, which the pool relies on to keep all worker threads busy even when the split isn't perfectly even. Parallel streams and Arrays.parallelSort both use the common ForkJoinPool internally.
More Related questions...