Java – Whether Spliterators from Spring JPA’s Iterable results are safe to use with parallelStream

Whether Spliterators from Spring JPA’s Iterable results are safe to use with parallelStream… here is a solution to the problem.

Whether Spliterators from Spring JPA’s Iterable results are safe to use with parallelStream

Similar to Are parallelStreams on OneToMany collections safe? But my question is specific to the results of Spring JPA Repository queries, such as

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

Can I safely use it in parallel? For example

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

Solution

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

One way to think about it is that students.findAllWithProgramAndSchedule() may trigger lazy loading. Under the hood, this will use a JDBC connection that is not inherently thread-safe, so students.findAllWithProgramAndSchedule() cannot be thread-safe.

Related Problems and Solutions