When you make a new thread in the method enclosed by @Transactional
, transaction does not propagate to the new thread.
For example, in the below case, write1 will rollback but write2 won't.
@Transactional
public void methodA() {
write1();
CompletableFuture.runAsync(() -> write2(), Executors.newSingleThreadExecutor());
if (true) {
throw new RuntimeException();
}
}
We need to make clear whether this is the specification or the bug.
Reference: Spring Transaction Management Over Multiple Threads
Comment From: sbrannen
When you make a new thread in the method enclosed by
@Transactional
, transaction does not propagate to the new thread.
This is by design: Spring's transaction support synchronizes transactional resources for the current thread via a ThreadLocal
variable (and not via an InheritableThreadLocal
).
Thus, the behavior you have encountered is expected and hinted at in a few places in the reference manual; however, we could make this more explicit.
In light of that, I am making this a "documentation" issue for 5.3.
Comment From: kanjih
That's cool, thanks!
Comment From: rohitp27
@sbrannen Is there a specific place where one must document such a behaviour?
From my understanding it would make the most sense to have it as a point-of-information in the transaction strategies section (Docs link).
However, there is a specific reference to ThreadLocal
in the hibernate transaction-management strategies section in the same doc (Docs link).
I'd like to take this up if possible. Even if not, I'd appreciate some documentation-practices guidance regarding the above question.
Comment From: sbrannen
@rohitp27, to be honest, I'd have to read through all the documentation we have on transaction management in order to determine where best to document it.
However, I imagine we'd want to add a NOTE in the introductory section in the reference manual and potentially cross reference that note from other relevant sections of the reference manual, and we'd likely want to add a similar note to the Javadoc for @Transactional
.
Comment From: stahloss
What if someone would want to be able to multithread within a transaction? I'd definately like to be able.