如何在多线程中使用spring事务 [英] How to use spring transaction in multithread

查看:941
本文介绍了如何在多线程中使用spring事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法如下:

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();
}

方法B可以正常运行吗?根据我的理解,methodB将附加methodA的事务,如果methodA在methodB之前退出怎么办?我想只有methodA可以被事务提交。但是因为之前提交的事务,methodB不会提交。

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.

我可以对methodB使用@Transactional(propagation = Propagation.REQUIRES_NEW)。这可以让methodB有一个新的事务。但根据spring doc,方法A的转换将在调用methodB时暂停。我觉得这里很困惑。

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.

推荐答案

不, methodB()将不会在与 methodA()相同的事务中执行。 Spring的 @Transactional 仅适用于单个线程 - 当线程首次使用 @Transactional 进入方法时,它会创建一个会话(或者带有 @Transactional 的类中的方法),然后在离开该方法时提交它。

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.

在您的示例中,事务将在您在线程池中计划作业后结束。 methodB()将拥有它自己的交易。

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

这篇关于如何在多线程中使用spring事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆