48

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.

1
  • what exactly do you want it to do? Commented May 2, 2012 at 7:35

1 Answer 1

38

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.

8
  • Can you advise how to monitor if they are not the same transaction? What I found was that the transaction was not commit.
    – Jacky
    Commented May 2, 2012 at 7:08
  • @Jacky Which of the two transactions does not commit?
    – jmruc
    Commented May 2, 2012 at 7:12
  • Transaction of methodB does not commit.
    – Jacky
    Commented May 2, 2012 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 static.springsource.org/spring/docs/3.1.x/…
    – jmruc
    Commented May 2, 2012 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
    Commented May 2, 2012 at 14:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.