Java Concurrency Interview

Concurrency in real systems question 126 of 180 mid

Why does @Transactional not work across threads?

Spring keeps the active transaction and its connection in TransactionSynchronizationManager, which is ThreadLocal-backed. Work handed to another thread, by @Async, an executor or a parallel stream, starts outside that transaction. It will either run with no transaction at all or open its own on a second connection, which cannot see the first one's uncommitted writes and can deadlock against it at the database level.

That last part is the war story to tell: a parent transaction holding row locks, a child thread on another connection waiting for those same rows, and the parent waiting for the child. Neither is a Java deadlock, so a thread dump shows nothing and the database's lock monitor shows everything.

The rule: one transaction, one thread. Do the concurrent work outside the transaction and commit once, or give each task its own short transaction and make the whole thing idempotent.

spring transactions

Quiz yourself on Concurrency in real systems Suggest a correction