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

Is Collectors.joining(",") thread-safe?

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

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

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

不怕运行陷入并发问题?

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

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.

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