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

标签 java concurrency java-8 java-stream

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 类中提供的任何其他收集器一样使用此收集器,而不必担心遇到并发问题。 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 .因此,即使同一个收集器被多个流操作重用,它们也不会干扰。

关于java - Collectors.joining (",") 是线程安全的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31051857/

相关文章:

python - sqlalchemy并发更新问题

java - 在 Java FutureTask 中,如果任务超时,任务是否会被取消?

java - 流和不同的操作

java - 使用 jackson ObjectMapper 时保留的堆大小更大

Java JTable 列标题不显示

c# - 如果两个或更多人同时更新一条记录会怎样?

java - 尝试将嵌套 for 循环转换为 Java 8 流时出错

java - Eclipse 找不到文件?

java - JVM super 构造函数调用

java - java中使用谓词(java.util.function.Predicate)的 "best case scenario"是什么