Java 8 parallel streams use the same threads for sequences
•
Java
Say we have such things:
LongStream.range(0,10).parallel() .filter(l -> { System.out.format("filter: %s [%s]\n",l,Thread.currentThread().getName()); return l % 2 == 0; }) .map(l -> { System.out.format("map: %s [%s]\n",Thread.currentThread().getName()); return l; });
If you run this program, the output will be as follows:
filter: 6 [main] map: 6 [main] filter: 5 [main] filter: 4 [ForkJoinPool.commonPool-worker-2] map: 4 [ForkJoinPool.commonPool-worker-2] filter: 1 [ForkJoinPool.commonPool-worker-3] filter: 2 [ForkJoinPool.commonPool-worker-1] filter: 0 [ForkJoinPool.commonPool-worker-3] filter: 3 [ForkJoinPool.commonPool-worker-2] filter: 8 [main] filter: 7 [ForkJoinPool.commonPool-worker-2] filter: 9 [ForkJoinPool.commonPool-worker-2] map: 0 [ForkJoinPool.commonPool-worker-3] map: 2 [ForkJoinPool.commonPool-worker-1] map: 8 [main]`
As we can see, each task sequence of each long is executed by the same thread Is this something we can rely on, or is it a coincidence? Can threads share tasks during execution?
Solution
Side effects from the stream package summary section:
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码