Video in progress
Is an `EntityManager` injected into a Spring bean thread-safe? When is using it from several threads dangerous?
What gets injected with @PersistenceContext (or through the constructor in Spring Boot) is a shared proxy: on each call it routes to the real EntityManager bound to the current thread's transaction, so it's safe in a singleton. The real EntityManager and the entities in it are not thread-safe, though, and handing them to another thread is dangerous.
📖 Answer
The safe case:
@Repository
class OrderDao {
@PersistenceContext
private EntityManager em; // a proxy, OK even in a singleton
}
On every em.find() call, Spring checks whether the current thread has a transaction and uses that transaction's EntityManager. Two parallel HTTP requests get two different persistence contexts.
The dangerous cases:
// 1) creating it by hand and keeping it in a field
private final EntityManager em = emf.createEntityManager(); // one for all threads!
// 2) a parallel stream inside a transaction
@Transactional
public void recalc(List<Long> ids) {
ids.parallelStream().forEach(id -> {
Order o = em.find(Order.class, id); // no transaction on ForkJoinPool threads
o.recalculate(); // the change isn't saved
});
}
In the second example the Spring transaction lives in a ThreadLocal, and other threads can't see it. They run without a transaction: reads work, while writes either get lost or throw TransactionRequiredException. And modifying one entity object from two threads can corrupt the internals of the persistence context.
Passing an entity to @Async or a CompletableFuture has the same problem: there it's detached and its lazy associations fail.
If you need parallel processing, I give the threads the ids and each one opens its own transaction (TransactionTemplate). Or I hand the work to the database as a single bulk SQL statement, which is often faster than parallel Java.
Sign up to mark studied questions and save your progress.