result-java icon indicating copy to clipboard operation
result-java copied to clipboard

ResultCollector not compliant with parallelStream requirements

Open ilkosta opened this issue 5 years ago • 0 comments

hi,

I'm trying to learn java and i found your article very interesting and useful, able to solve in a clear and simple way what seems to me a deficiency in the current implementation of java.

By trying to use the library I noticed that the characteristics of ResultCollector were not specified.

public Set<Characteristics> characteristics() { return Set.of(); }

So I tried to verify its behavior with a parallel stream and I noticed a wrong result.

  @Test
  void collectorSyncronization() {
    Supplier<Integer> fn = () -> new Random().nextInt(10);
 
    // ok this is std collector
    assertDoesNotThrow(() -> Stream.generate(fn).parallel().limit(100).collect(Collectors.toList()));

    // trying the same with a CheckedSupplier and a Result
    Supplier<Result<Integer,Exception>> randomNumbersSupp=() -> Result.attempt(() -> fn.get());
    Stream<Result<Integer,Exception>> streamOfValues = Stream.generate(randomNumbersSupp)
                                                             .limit(100);

    // with a serial stream all is ok
    List<Integer> values = assertDoesNotThrow( () ->
                                streamOfValues
                                      .collect(new ResultCollector<>())
                                      .getValue().get()
                      );

    // with a parallelStream something go wrong  
    assertThrows( Exception.class, () ->
                          streamOfValues
                                      .parallel()
                                      .collect(new ResultCollector<>())
                                      .getValue().get()
                      );

  }

ilkosta avatar Jul 14 '20 08:07 ilkosta