Fork/join and parallel streams question 109 of 180 senior
Can you run a parallel stream in your own pool, and should you?
- No, parallel streams always use the common pool
- Correct: Yes, by submitting the whole pipeline to your own
ForkJoinPool, which is a documented-enough trick but not an officially supported API - Yes, via
stream.parallel(executor) - Yes, with a system property per stream
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.
Quiz yourself on Fork/join and parallel streams Suggest a correction