简体   繁体   English

如何在多线程中使用spring事务

[英]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?方法B可以正常工作吗? Per my understanding, methodB will attach the transaction of methodA, what if methodA exits before methodB?根据我的理解,methodB会附加methodA的事务,如果methodA先于methodB退出呢? I guess only methodA can be commited by the transaction.我猜只有 methodA 可以被事务提交。 But methodB will not commit because the transaction commited before.但是methodB不会提交,因为之前提交的事务。

Can I use @Transactional(propagation = Propagation.REQUIRES_NEW) for methodB.我可以将 @Transactional(propagation = Propagation.REQUIRES_NEW) 用于 methodB。 This can let methodB have a new transaction.这可以让methodB 有一个新的事务。 But according to spring doc, the transcation of methodA will suspend when it invoke methodB.但是根据spring doc,methodA的事务在调用methodB时会挂起。 I feel very confuse here.我在这里感到很困惑。

Can anyone help me on this issue?任何人都可以帮助我解决这个问题吗? Thanks in advance.提前致谢。

No, methodB() will not be executed in the same transaction as methodA() .不, methodB()将不会在相同的事务中执行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. Spring 的@Transactional仅适用于单个线程 - 当线程第一次进入带有@Transactional的方法(或带有@Transactional的类中的方法)时,它会创建一个会话,然后在离开该方法时提交它。

In your example, the transaction will end after you schedule the job in the thread pool.在您的示例中,事务将在您在线程池中安排作业后结束。 methodB() will have it's own transaction. methodB()将有它自己的事务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM