Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 323
Roy Stark Avatar asked Jun 25 '15 13:06

Roy Stark


1 Answers

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.

like image 183
Tagir Valeev Avatar answered Oct 03 '22 09:10

Tagir Valeev