Handling Multithreaded Transactions in Spring Boot with Manual SqlSession Management
This article explains how to manage multithreaded database insert operations in Spring Boot, demonstrates why the @Transactional annotation fails in a multithreaded context, and provides a solution using manual SqlSession transaction control with code examples and test results.
The article begins by describing a scenario where a large volume of data needs to be inserted into a database using multiple threads, and a failure in any thread should trigger a full rollback, highlighting that the standard @Transactional annotation does not work across threads.
It then introduces common utility classes and methods, including a method to evenly split a list into sub‑lists ( averageAssign) and a thread‑pool configuration class ( ExecutorConfig) that creates a singleton ExecutorService based on the number of available processors.
Next, a failing multithreaded transaction example is shown where the main thread performs a delete operation before spawning worker threads; when a worker thread throws an exception, the delete is not rolled back because @Transactional is ineffective in this context.
To solve the problem, the article proposes using a manually managed SqlSession obtained from a SqlContext bean. By disabling auto‑commit, executing the delete and batch inserts within the same session, and explicitly calling connection.rollback() when any thread reports a failure, full transactional consistency is achieved.
Full source code for the manual‑transaction approach is provided, including the creation of Callable tasks, invocation via ExecutorService.invokeAll, result checking, and explicit commit or rollback handling.
Test results are displayed with screenshots showing that, after an exception, the delete operation is rolled back and the database state remains unchanged, confirming the success of the manual transaction strategy.
A successful execution example is also given, where all threads complete without errors, the delete is committed, and the new records are inserted, demonstrating the correct behavior of the solution.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Architect's Guide
Dedicated to sharing programmer-architect skills—Java backend, system, microservice, and distributed architectures—to help you become a senior architect.
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.
