Video in progress
MDC logs, SecurityContext or @Transactional stopped working inside a parallel stream. Why, and how do you fix it?
All of these are stored in a ThreadLocal. A parallel stream runs some of the elements on the calling thread and the rest on ForkJoinPool.commonPool workers, where the MDC is empty, there's no SecurityContext, and the connection bound to the transaction isn't visible. The result is the worst kind of bug: "sometimes works".
📖 Answer
Typical code:
@Transactional
public void recalc(List<Long> ids) {
ids.parallelStream().forEach(id -> {
log.info("recalc {}", id); // traceId is sometimes there, sometimes not
Account a = accountRepo.findById(id).orElseThrow();
a.setScore(scoring.calc(a)); // sometimes saved, sometimes not
});
}
What happens:
- MDC:
traceIdis only on the calling thread. Log lines from the workers drop out of the trace, and those are exactly the ones you need during an incident. - SecurityContext: the default is
MODE_THREADLOCAL. On a worker,SecurityContextHolder.getContext()is empty, so@PreAuthorizeor auditing ("who changed it") fails or writesnull. - @Transactional: the transaction and the
EntityManagerare bound to a thread. On a worker, a repository call runs outside the transaction, with a separate connection; the changed entity isn't in the transaction's persistence context, so dirty checking doesn't save it. A lazy association gives aLazyInitializationException. On top of that,EntityManagerisn't thread-safe.
The hardest part is that the calling thread also takes part in the work. So some of the elements work correctly and the test passes on a small data set.
The fix, in order of preference:
- Don't parallelize. There's no place for a parallel stream in transactional code that talks to a DB. If you need speed: a single
findAllById, a batch update or SQL. - Pass context explicitly. If you need parallelism, parallelize the pure computation and keep the context-dependent part on the calling thread:
Map<Long, Integer> scores = accounts.parallelStream() // CPU computation only
.collect(toMap(Account::getId, scoring::calc));
accounts.forEach(a -> a.setScore(scores.get(a.getId()))); // on the transaction's thread
- Your own executor and context propagation:
MDC.getCopyOfContextMap()+MDC.setContextMap(), Spring Security'sDelegatingSecurityContextExecutor, Micrometer context-propagation. You can't add this to the common pool.
In Java 21+ ScopedValue is also worth considering for new code (final in Java 25), but parallel stream workers don't inherit it automatically either.
Sign up to mark studied questions and save your progress.