Collectors.joining(",") 线程安全吗?

2022-01-22 00:00:00 concurrency java-8 java java-stream

java.util.stream.Collectors::joining 实现是线程安全的吗?我可以做类似的事情吗

Are java.util.stream.Collectors::joining implementations thread-safe? Can I do something like

public final class SomeClass {
  private static final Collector<CharSequence, ?, String> jc = Collectors.joining(",");

  public String someMethod(List<String> someList) {
       return someList.parallelStream().collect(jc);
  }
}

不用担心遇到并发问题?

without fear of running into concurrency issues?

推荐答案

您可以将此收集器用作 Collectors 类中提供的任何其他收集器,而不必担心遇到并发问题.Collector 不需要关心线程安全,除非它具有 CONCURRENT 特性.它只需要使其操作不受干扰、无状态和关联.其余的将由 Stream 管道本身完成.它将以不需要额外同步的方式使用收集器功能.特别是当 accumulatorcombiner 函数被调用时,可以保证此时没有其他线程正在对相同的累加值进行操作.这在 Collector 文档中指定:

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:

基于 Collector 实现归约的库,例如 Stream.collect(Collector),必须遵守以下约束:

Libraries that implement reduction based on Collector, such as Stream.collect(Collector), must adhere to the following constraints:

<...>

<...>

  • 对于非并发收集器,从结果提供者、累加器或组合器函数返回的任何结果都必须是串行线程限制的.这使得收集可以并行发生,而 Collector 不需要实现任何额外的同步.归约实现必须管理输入是否正确分区,分区是单独处理的,并且只有在累积完成后才会合并.
  • 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.

请注意,收集器本身和它提供的功能一样是无状态的,因此将它放在静态字段中也是安全的.状态保存在外部累加器中,由 supplier 返回并传递回 accumulatorcombinerfinisher.所以即使同一个收集器被多个流操作重用,它们也不会干扰.

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.

相关文章