r/SpringBoot • u/iamwisespirit • Jan 09 '26
Question @Transactional method
What happen when I run executorsrrvice inside @Transactional method what would you offer like this scenario
2
Upvotes
r/SpringBoot • u/iamwisespirit • Jan 09 '26
What happen when I run executorsrrvice inside @Transactional method what would you offer like this scenario
10
u/[deleted] Jan 09 '26 edited Jan 09 '26
It might help to understand how
@Transactionalactually works. It creates a Spring proxy that binds a transaction to thread (by holding it in thread local storage), so you can run your normal Java code. If your code exits the@Transactionalblock normally, the Spring proxy will commit the transaction. If your code throws an exception, the Spring proxy will rollback the transaction.When you push a task onto an executor service, you're running that code on a different thread. You're basically breaking the Spring model here. How do the other threads know which transaction is running?
But it's worse than that. How will you maintain consistency? If you're sharing a transaction between threads, that's shared state. If one of the tasks on the worker thread throws an exception, how will you roll back? How will the other threads now that the transaction is now in an invalid state?
You should use some structured form of concurrency to manage this. For example, if you organize your concurrency with
CompleteableFuture, it can properly unwind the concurrent operations if one of them fails, andCompleteableFuturewill provides hooks where you commit or rollback the transaction.You're walking into dangerous territory here, and it will take some significant experience with concurrency to manage this correctly.
1
u/disposepriority Jan 09 '26
When you say run the executor service do you mean you would submit a task to it?
The `@Transactional` annotation is a thread local (or bound to a thread some other way, I don't remember) so if you were to start a new thread from within it would not use the same transaction.
1
u/LeadingPokemon Jan 09 '26
Transactions are single threaded concept. Your new runnable submitted to the executor would not be part of the same transaction.
1
u/Cautious-Necessary61 Jan 09 '26
are you trying to update a database and also something non transactional in a single request?
1
u/d-k-Brazz Jan 10 '26
tl;dr - you shouldn’t
In classic Spring (non reactive) you should never mix any abstractions which use TheeadLocal with any kind of concurrency. This includes @Transactional, security context, request/session scoped beans etc.
If you are still mixing it, you must be aware of consequences (guys around already explained it)
3
u/This_Link881 Jan 09 '26
What problem would you like to solve?
1
u/MassimoRicci Jan 09 '26
What do you use multithreading for? What problem do you solve?