Java Reference
In-Depth Information
See the javadoc for the
java.util.stream.Stream
interface for a complete list of the oper-
ations.
Improving Throughput with Parallel Streams and
Collections
Problem
You want to combine
Stream
s with parallelism, and still be able to use the nonthread-safe
Collections API.
Solution
Use a parallel stream.
Discussion
The standard Collections classes such as most
List
,
Set
, and
Map
implementations are not
thread-safe for update; if you add or remove objects from one in one thread while another
thread is accessing the objects stored in the collection, failure will result. Multiple threads
reading from the same collection with no modification is OK. We discuss multithreading in
The Collections Framework does provide “synchronized wrappers,” which provide automat-
ic synchronization but at the cost of adding thread contention, which reduces parallelism. To