46

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.

Jacky
  • 8,619
  • 7
  • 36
  • 40

1 Answers1

35

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.

jmruc
  • 5,714
  • 3
  • 22
  • 41
  • Can you advise how to monitor if they are not the same transaction? What I found was that the transaction was not commit. – Jacky May 02 '12 at 07:08
  • @Jacky Which of the two transactions does not commit? – jmruc May 02 '12 at 07:12
  • Transaction of methodB does not commit. – Jacky May 02 '12 at 13:33
  • I can't really know what is the problem, but a wild guess would be that ClassB is not a Spring bean - see http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/transaction.html#tx-decl-explained – jmruc May 02 '12 at 14:18
  • It is a Spring bean. It worked well after I made it excuting in the same thread which means I removed the use of executorService. – Jacky May 02 '12 at 14:22
  • @Jacky Sorry, no more ideas - if you could post more about your transaction manager, spring beans, and classes, maybe someone will be able to help you. – jmruc May 02 '12 at 14:39
  • Thanks Kiril. I tried @Transactional(propagation = Propagation.REQUIRES_NEW) but it did not work either. Spring itself provides Task Executor. I did not use it. I just create Executor on my own, I'm not sure if it does matter. I will continue to investigate. – Jacky May 03 '12 at 13:57
  • It's my bad. Kiril, you are right. It will create a new transaction for the new thread. Another bug caused the problem which misled me. – Jacky May 04 '12 at 03:30