Video in progress
What happens to the transaction and the EntityManager if you split the work inside a @Transactional method across several threads?
The transaction and its bound EntityManager/connection are tied to the current thread through ThreadLocal. A new thread doesn't see them: it runs outside the outer transaction, and the EntityManager itself is not thread-safe, so you can't share it between threads.
📖 Answer
@Transactional
public void recalculate(List<Long> ids) {
ids.parallelStream().forEach(id -> {
Account a = accountRepo.findById(id).orElseThrow();
a.setBalance(calc(a)); // does this change get saved?
});
}
This code has several problems:
- part of the
parallelStreamwork runs on the calling thread (inside the transaction) and the rest on commonPool threads. There,findByIdopens and closes its own short read-only transaction, the entity is detached right away, andsetBalanceis saved nowhere; - the result: the part that landed on the calling thread gets committed, and the rest silently disappears. It's the worst kind of bug, "sometimes it saves, sometimes it doesn't";
- one transaction is still one connection, and a connection runs one query at a time, so the DB side gets no benefit from the parallelism.
Lazy loading fails for the same reason: if you hand an entity to another thread, you get LazyInitializationException.
The right approaches:
- if you really need parallelism, split the work into chunks and let each chunk run in its own transaction: a
@Transactional(propagation = REQUIRES_NEW)method in a separate bean, orTransactionTemplate, through an executor; - pass IDs or DTOs between threads, not entities;
- often you don't need parallelism at all: a single
UPDATE ... WHERE id IN (...)or a JDBC batch is much faster.
And don't forget one thing: several independent transactions means no atomicity. Half can commit while the other half fails, so the processing has to be idempotent.
Sign up to mark studied questions and save your progress.