You can use this collector as any other collector provided in Collectors
class without fear of running into concurrency issues. The Collector
need not to care about thread safety unless it has CONCURRENT
characteristic. It just need to have its operations non-interfering, stateless and associative. The rest will be done by Stream pipeline itself. It will use the collector functions in the way which does not require the additional synchronization. In particular when accumulator
or combiner
function is called, it's guaranteed that no other thread is operating on the same accumulated value at the moment. This is specified in Collector documentation:
Libraries that implement reduction based on Collector
, such as Stream.collect(Collector)
, must adhere to the following constraints:
<...>
- For non-concurrent collectors, any result returned from the result supplier, accumulator, or combiner functions must be serially thread-confined. This enables collection to occur in parallel without the
Collector
needing to implement any additional synchronization. The reduction implementation must manage that the input is properly partitioned, that partitions are processed in isolation, and combining happens only after accumulation is complete.
Note that the collector itself is stateless as well as functions it provides, thus it's also safe to have it in the static field. The state is preserved in the external accumulator which is returned by supplier
and passed back to accumulator
, combiner
and finisher
. So even if the same collector is reused by several stream operations, they don't interfere.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…