Java Concurrency Interview

Fork/join and parallel streams question 109 of 180 senior

Can you run a parallel stream in your own pool, and should you?

There is no API for it. The trick works because a parallel stream executes in the pool of the thread that runs it:

ForkJoinPool pool = new ForkJoinPool(8);
try {
    List<Result> out = pool.submit(() -> items.parallelStream().map(this::work).toList()).get();
} finally {
    pool.shutdown();
}

It is widely used to isolate one workload from the common pool, and it works on every current JVM, but it relies on an implementation detail rather than a specification. Say that in an interview: it is the kind of nuance the question is testing for. If you need genuine isolation and control, an explicit executor with explicit tasks is clearer than a stream.

parallel-streams forkjoin

Quiz yourself on Fork/join and parallel streams Suggest a correction