Is Collectors.joining(",")线程安全吗? [英] Is Collectors.joining(",") thread-safe?

查看:498
本文介绍了Is Collectors.joining(",")线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

java.util.stream.Collectors :: join 实现线程安全?我可以做类似

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);
  }
}

而不必担心并发问题?

推荐答案

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

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收藏者)必须遵守以下限制:

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 返回的外部累加器中,并返回到 accum combiner finisher 。因此,即使同一个收集器被多个流操作重用,它们也不会干扰。

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.

这篇关于Is Collectors.joining(&quot;,&quot;)线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆