Java Reference ยท Streams and Functional
Java parallel streams
Reference for Java parallel streams: parallel(), parallelStream(), the common pool, ordering, safe reductions and the mistakes that cause wrong results.
A parallel stream splits its source into chunks, processes the chunks on several threads, and combines the partial results. You create one with collection.parallelStream() or by calling parallel() on any stream. sequential() switches back, and isParallel() tells you the current mode. Only the last call before the terminal operation counts, because the whole pipeline runs in one mode.
Parallel streams run on the shared common ForkJoinPool, whose size is by default one less than the number of processors. They can speed up CPU-heavy work on large, easily splittable data (arrays, ArrayList, ranges). For small inputs, I/O, or poorly splittable sources such as LinkedList or Stream.iterate(), they are usually slower than a sequential stream.
long primes = IntStream.rangeClosed(2, 200_000) .parallel() .filter(n -> isPrime(n)) .count();
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
// Stream (and BaseStream) S parallel() S sequential() boolean isParallel() S unordered() // Collection Stream<E> parallelStream()
| Member | Description |
|---|---|
parallel() |
Returns a stream (usually the same one) that will run in parallel. |
sequential() |
Returns a stream that will run sequentially. |
isParallel() |
true if the terminal operation would run in parallel. |
unordered() |
Declares that encounter order does not matter, allowing cheaper distinct(), limit() and groupingBy(). |
parallelStream() |
A possibly parallel stream over a collection. |
Usage notes
- Measure first. Overhead of splitting, scheduling and merging often exceeds the gain below tens of thousands of elements or for cheap operations. Benchmark with realistic data (for example with JMH) before keeping
parallel(). - Good sources: arrays,
ArrayList,IntStream.range(),HashMapkey sets split well.LinkedList,BufferedReader.lines()andStream.iterate()split poorly. - Stateless and non-interfering. Lambdas must not modify the source or shared state. Writing to a plain
ArrayListorHashMapfromforEachis a data race. - Associativity.
reduce()needs an associative operator and a real identity. Subtraction and string-building with side effects give wrong or varying results. - Ordering.
findFirst(),limit()andskip()respect encounter order and can be expensive in parallel;findAny()andunordered()are cheaper.forEach()has no ordering promise;forEachOrdered()has. - Blocking work hurts everyone. The common pool is shared by the whole JVM, including other parallel streams and
CompletableFutureasync methods; blocking I/O inside it starves them. Use a dedicated executor for blocking tasks. - Exceptions from worker threads are rethrown from the terminal operation.
- Never rely on thread names or printing order in tests; the schedule changes between runs.