Java Reference
In-Depth Information
Note that, in reality, calling the method parallel on a sequential stream doesn't imply any
concrete transformation on the stream itself. Internally, a boolean flag is set to signal that you
want to run in parallel all the operations that follow the invocation to parallel. Similarly, you can
turn a parallel stream into a sequential one by just invoking the method sequential on it. Note
that you might think that you could achieve finer-grained control over which operations you
want to perform in parallel and which one sequentially while traversing the stream by
combining these two methods. For example, you could do something like the following:
stream.parallel()
.filter(...)
.sequential()
.map(...)
.parallel()
.reduce();
But the last call to parallel or sequential wins and affects the pipeline globally. In this example,
the pipeline will be executed in parallel because that's the last call in the pipeline.
Configuring the thread pool used by parallel streams
Looking at the stream's parallel method, you may wonder where the threads used by the parallel
stream come from, how many there are, and how you can customize the process.
Parallel streams internally use the default ForkJoinPool (you'll learn more about the fork/join
framework in section 7.2 ) , which by default has as many threads as you have processors, as
returned by Runtime.getRuntime().availableProcessors().
But you can change the size of this pool using the system property
java.util.concurrent.ForkJoinPool.common.parallelism, as in the following example:
System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "12");
This is a global setting, so it will affect all the parallel streams in your code. Conversely, it
currently isn't possible to specify this value for a single parallel stream. In general, having the
size of the ForkJoinPool equal to the number of processors on your machine is a meaningful
default, and we strongly suggest that you not modify it unless you have a very good reason for
doing so.
Search WWH ::




Custom Search