When Does @Transactional Commit? Before or After Unlock?
This article explains the timing of Spring's @Transactional commit relative to lock release, analyzes why committing after unlock can cause overselling, shows how to trace the transaction lifecycle in the source code, and offers practical solutions to ensure atomicity in high‑concurrency scenarios.
The article examines a common concurrency problem in e‑commerce systems where multiple threads simultaneously invoke a method that queries inventory, decrements stock, and creates an order.
Although the method is annotated with
@Transactionaland wrapped in a lock, the transaction commit may occur after the lock is released, leading to overselling.
It demonstrates that the transaction actually starts after the lock is acquired (the
lockblock) and that the first SQL statement (e.g.,
SELECT) triggers the real transaction start. If the commit happens after
unlock, another thread can read stale inventory data and also place an order.
The article walks through the Spring source code, highlighting key methods such as
org.springframework.jdbc.datasource.DataSourceTransactionManager#doBegin,
TransactionAspectSupport#invokeWithinTransaction, and the point where the connection's auto‑commit is set to false. It explains that setting
con.setAutoCommit(false)only prepares the connection; the transaction begins with the first DML operation.
It also clarifies Spring's default rollback rules (RuntimeException or Error) and shows how to debug transaction boundaries by setting breakpoints on methods like
TransactionAspectSupport#invokeWithinTransactionand
DataSourceTransactionManager#doBegin.
To prevent overselling, the article suggests keeping the entire transactional logic inside the lock, using proper distributed locks, or adjusting the isolation level to SERIALIZABLE. It also mentions alternative approaches such as programmatic transaction management.
Throughout, the article provides visual diagrams and code snippets (shown as images) to illustrate the flow, and it removes unrelated promotional content while preserving the technical core.
macrozheng
Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.