Custom ForkJoinPool For Parallel Streams

Submit a parallel stream to a dedicated ForkJoinPool so heavy aggregation stays isolated from the shared common pool.

JavaResilience

Code

snippet
import java.util.concurrent.ForkJoinPool;
import java.util.stream.LongStream;

public class IsolatedParallelSum {

    public static void main(String[] args) {
        // parallel streams borrow the common pool by default: an explicit dedicated pool isolates the heavy aggregation
        long total;
        try (ForkJoinPool customPool = new ForkJoinPool(4)) {
            total = customPool.submit(() ->
                    LongStream.rangeClosed(1, 100_000).parallel()
                            .map(n -> n * n)
                            .sum()).join();
            System.out.println("custom pool parallelism: " + customPool.getParallelism());
        }
        System.out.println("sum of squares: " + total);
    }
}

How it works

Structurally, expect the class IsolatedParallelSum and the function main and nothing else.

Resources are declared in a try-with-resources header, so they close on every exit path without a finally block.

Points of care

  • Its one and only prerequisite is the language toolchain.

Applying it

Entry signature: public static void main(String[] args)

The output comes back labeled — custom pool parallelism:, sum of squares: — when the file runs.

Statements that matter most here

.map(n -> n * n)
.sum()).join();

Interactive Tools for This Topic

FAQ

What does Custom ForkJoinPool For Parallel Streams print when run?
Run it as a complete program — the output lines carry labels such as `custom pool parallelism:`, `sum of squares:`.