Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using threads to run a method that is not part of the transaction?

i have a case where at my JAVA application, inside a transaction i want to call another service (JMS, WebService, SMS gate way, ...etc), i don't want to depend on the result of the call (Success, Fail, Exception thrown, ... etc), so if it fails somehow it won't affect my transaction completion,

what is the best approach to use this, am using Spring framework,

also i want to ask if i used threads for handling this, but my deployment will be on clusters(i.e different nodes with separate JVMs), what's the best way for handling (Lock, synchronization),

Regards,

like image 899
Amr Faisal Avatar asked Jan 29 '26 13:01

Amr Faisal


1 Answers

You can could spawn a new thread (preferably via a java.util.Executor or a Spring TaskExecutor) to perform the subsidiary task. Spring's transaction synchronization works using non-inheritable ThreadLocal variables, so a new thread will not participate in the current transaction.

Alternatively, and perhaps more elegantly, you can specify an explicit transaction isolation level around the subsidiary task, something like:

@Transactional(propagation=Propagation.NOT_SUPPORTED)
public void doTheThing() { /.../ }

This will suspend the existing transaction for the duration of that method, although you'd still need to be careful with runtime exceptions not bubbling up into your main transaction boundary.

Regards your second question, locking and synchronisation in a cluster is a very complex topic, and not one I can really answer with the information you've given. I suggest opening a new question for this, and elaborate your requirements.

like image 69
skaffman Avatar answered Jan 31 '26 05:01

skaffman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!