Are Spliterators from Iterable results from Spring JPA safe to use in parallelStream

Viewed 166

Similar to Are parallelStreams on OneToMany collections safe? but my question is specific to the result from a Spring JPA Repository query e.g.

public interface Students extends JpaRepository<Student, UUID> {
    @EntityGraph("Student.withProgramAndSchedule")
    @Query("from Student s")
    Iterable<Student> findAllWithProgramAndSchedule();
}

Can I safely use it with parallel? e.g.

StreamSupport.stream(students.findAllWithProgramAndSchedule().spliterator(), true)
1 Answers

JPA entity managers and the entities they manage are not thread safe.

One way to think about it is that students.findAllWithProgramAndSchedule() might trigger a lazy load. Under the hood this will use a JDBC connection which itself is not thread safe, therefore the students.findAllWithProgramAndSchedule() can't be thread safe.

Related