Senior
If you create two independent parallel streams in one program, will they use the same ForkJoinPool? What problems does this create?
sobes.tech AI
Answer from AI
In Java, parallel streams by default use the shared global ForkJoinPool.commonPool(). This means that if two independent parallel streams are created in the same program, they will use the same thread pool.
Problems this creates:
- Mutual influence on performance: if both streams actively use the pool, they compete for the same threads, which can lead to decreased performance.
- Locks and deadlocks: if tasks within the stream block or wait for each other, this can lead to deadlocks, especially if the pool size is limited.
- Lack of isolation: it is not possible to configure separate pool parameters (e.g., size) for each stream, reducing flexibility.
If isolated execution is required, you can create your own ForkJoinPool and run the stream through the submit or invoke method of this pool:
ForkJoinPool customPool = new ForkJoinPool(4);
customPool.submit(() -> stream.parallel().forEach(...)).get();