0

Spring repository find calls inside java parallelStream for unit tests do not return the expected results. They return empty/no results. I suspect it could be some configuration needed for spring tests when using parallelStream? Any ideas?

//Is never empty
List<ObjectHistory> allHist = objectHistoryRepository.findAll();

//problematic
objects.parallelStream()
        .forEach(i-> {
              //Is  empty except for one or none
              List<ObjectHistory> allHist = objectHistoryRepository.findAll();

              //Optional is empty except for one or none
              Optional<ObjectHistory> objHistoryOptional = objectHistoryRepository.findFirstById(i.getId());
         });

//works fine
objects.stream()
        .forEach(i-> {
              //Is never empty
              List<ObjectHistory> allHist = objectHistoryRepository.findAll();

              //Optional is never empty
              Optional<ObjectHistory> objHistoryOptional = objectHistoryRepository.findFirstById(i.getId());
        });
Olezt
  • 1,638
  • 1
  • 15
  • 31
  • 1
    Can you provide a whole unit test? – RoninDev May 19 '20 at 08:08
  • @RoninDev The code above is part of the tested code, not the unit test itself. The problem with the parallelStream appears only when executed through the unit tests. I am sorry I cannot share a whole unit test but what it does is adding data to the repos and then execute the function that includes the code from my question. – Olezt May 19 '20 at 08:21
  • 2
    The unti tests in spring have @Transactional behavior on test. May be it affect you. https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#integration-testing. I asked about unit test to see your assertions statements because it can make sense. Also interest in annotations on test class – RoninDev May 19 '20 at 08:31
  • @Holger I updated the title. I hope the problem is clear now. You can see also the comments in the code to understand the different behavior. – Olezt May 19 '20 at 11:39
  • 1
    The code comments were not helpful as they did not clarify what was expected behavior and what unintended actual behavior. The issue reminds me of the [stream on JPA lazy list](https://stackoverflow.com/q/37925649/2711488) issue. – Holger May 19 '20 at 12:15
  • Looks like @RoninDev pointed me in the right direction. I was using javax @ Transactional and @ Before annotations. Changed to spring @ Transactional using also the @ Before/After Transaction and then everything is fine. Still don't understand why the normal stream() had different behavior in the first place. – Olezt May 19 '20 at 13:23

0 Answers0