java 如何在多线程中使用spring事务
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10407301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use spring transaction in multithread
提问by Hymany
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.
方法B可以正常工作吗?根据我的理解,methodB会附加methodA的事务,如果methodA先于methodB退出呢?我猜只有 methodA 可以被事务提交。但是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.
我可以将 @Transactional(propagation = Propagation.REQUIRES_NEW) 用于 methodB。这可以让methodB 有一个新的事务。但是根据spring doc,methodA的事务在调用methodB时会挂起。我在这里感到很困惑。
Can anyone help me on this issue? Thanks in advance.
任何人都可以帮助我解决这个问题吗?提前致谢。
采纳答案by jmruc
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()
不会在与 相同的事务中执行methodA()
。Spring@Transactional
仅适用于单个线程 - 当线程第一次进入方法 with @Transactional
(或类中的方法 with @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()
将有它自己的交易。