Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use spring transaction in multithread

I have a method as below:

ClassA.java @Transactional public void methodA(){             ExecutorService executorService = Executors.newFixedThreadPool(4);     executorService.execute(new Runnable() {         public void run() {             classB.methodB();         } }); } ClassB.java @Transactional public void methodB(){     updateDB(); } 

Can the methodB work well? Per my understanding, methodB will attach the transaction of methodA, what if methodA exits before methodB? I guess only methodA can be commited by the transaction. But methodB will not commit because the transaction commited before.

Can I use @Transactional(propagation = Propagation.REQUIRES_NEW) for methodB. This can let methodB have a new transaction. But according to spring doc, the transcation of methodA will suspend when it invoke methodB. I feel very confuse here.

Can anyone help me on this issue? Thanks in advance.

like image 911
Jacky Avatar asked May 02 '12 03:05

Jacky


People also ask

How are transactions implemented in multi-threaded environment?

Your parent processing thread will (1.) create new threads to do parallel DB inserts, (2.) create a CountDownLatch object (this will hold your parent thread until all child threads which are doing db inserts are finished) (3.) create a db connection object with auto commit mode as FALSE.

Is @transactional thread safe?

Spring uses the underlying database implementation for transactions, so they are as thread safe as the underlying database can be.


1 Answers

No, methodB() will not be executed in the same transaction as methodA(). Spring's @Transactional only works on a single thread - it creates a session when a thread first enteres a method with @Transactional (or a method in a class with @Transactional), and then commits it when it leaves that method.

In your example, the transaction will end after you schedule the job in the thread pool. methodB() will have it's own transaction.

like image 160
jmruc Avatar answered Sep 21 '22 03:09

jmruc