リダクション、並行性、および順序付け
ところが、このリダクションで使用される結果コンテナが、ConcurrentHashMap
のような、同時変更可能なコレクションであったとします。その場合、アキュムレータの並列呼出しでは、実際には同じ共有結果コンテナに結果を同時に蓄積できるため、コンバイナで複数の結果コンテナをマージする必要がなくなります。これにより、並列実行のパフォーマンスが向上する可能性があります。これを並行リダクションと呼びます。
Stream.collect(Collector)
実装が並行リダクションを実行するのは、次の場合だけです。
- ストリームが並列的であり、
- コレクタが
Collector.Characteristics.CONCURRENT
特性を持っていて、
- ストリームが順序付けされていないか、コレクタが
Collector.Characteristics.UNORDERED
特性を持つ。
Reduction, concurrency, and ordering
Suppose, however, that the result container used in this reduction was a concurrently modifiable collection -- such as aConcurrentHashMap
. In that case, the parallel invocations of the accumulator could actually deposit their results concurrently into the same shared result container, eliminating the need for the combiner to merge distinct result containers. This potentially provides a boost to the parallel execution performance. We call this a concurrent reduction.The
Stream.collect(Collector)
implementation will only perform a concurrent reduction if
- The stream is parallel;
- The collector has the
Collector.Characteristics.CONCURRENT
characteristic, and;- Either the stream is unordered, or the collector has the
Collector.Characteristics.UNORDERED
characteristic.
This is called a concurrent reduction. The Java runtime performs a concurrent reduction if all of the the following are true for a particular pipeline that contains the
collect
operation:
- The stream is parallel.
- The parameter of the
collect
operation, the collector, has the characteristicCollector.Characteristics.CONCURRENT
. To determine the characteristics of a collector, invoke theCollector.characteristics
method.- Either the stream is unordered, or the collector has the characteristic
Collector.Characteristics.UNORDERED
. To ensure that the stream is unordered, invoke theBaseStream.unordered
operation.