Skip to content

ResultCollector not compliant with parallelStream requirements #2

@ilkosta

Description

@ilkosta

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

  }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions