[英]What happens when a @Transactional annotated method is hit in parallel by multiple instances?
Please correct me if I am wrong somewhere. 如果我在某个地方不对,请纠正我。
I am having an issue where my transaction are not being saved to the data base and some sort of racing is occurring which screws up the data. 我遇到一个问题,即我的交易未保存到数据库中,正在发生某种竞争,使数据搞砸了。 The app is hit in parallel by multiple instances.
该应用程序被多个实例并行命中。 I have used @Transactional, which I know is to do a transaction with database and the transaction is committed when the method returns.
我使用了@Transactional,我知道它是与数据库进行事务处理的,并且该方法返回时将提交事务。
The question is, does hitting it through multiple instance still maintain this one transaction per hit thing, or it does not handle the situation and data will screw up because of racing? 问题是,通过多次实例击中它是否仍会保持每个击中事物的这一笔交易,还是无法处理这种情况并且数据会因为竞速而搞砸?
Can a solution be suggested for the given condition? 可以针对给定条件提出解决方案吗?
The @Transactional
is not related to synchronization. @Transactional
与同步无关。 It just makes sure that your flow either succeeds or fails. 它只是确保您的流程成功或失败。 Each hit has its own flow and its own success or failure.
每次点击都有自己的流程,也有自己的成功或失败。
I guess what you're experiencing is due to the use of shared data. 我想您遇到的是由于使用共享数据。
For example. 例如。 If you have a class
Foo
that looks like this: 如果您有一个
Foo
类,如下所示:
public class Foo {
private static boolean flag = true;
@Transactional
public void doSomething() {
flag = false;
}
}
In this case it doesn't matter that you have many Foo
instances because they all use the same flag
. 在这种情况下,有很多
Foo
实例都没关系,因为它们都使用相同的flag
。
Another scenario would be if you have one instance of Foo
(very common if you use something like Spring
) and you have data that is changed for this instance. 另一种情况是,如果您有一个
Foo
实例(如果使用像Spring
这样的实例,则很常见),并且您有针对该实例更改的数据。 You can look at the same Foo
example and just remove the static
from flag
: 您可以查看相同的
Foo
示例,只需从flag
删除static
:
public class Foo {
private boolean flag = true;
@Transactional
public void doSomething() {
flag = false;
}
}
In either of those cases you need to synchronize the data changes somehow. 在这两种情况下,您都需要以某种方式同步数据更改。 It has nothing to do with
@Transactional
. 它与
@Transactional
无关。
That transactions are database transactions and behavior is database engine dependant but it usually works this way: 事务是数据库事务,行为取决于数据库引擎,但通常以这种方式工作:
@Transactional
is not about synchronization . @Transactional
与同步无关 。 SELECT * FROM MYTABLE FOR UPDATE;
. UPDATE MYTABLE SET A = A + 1;
And it blocks .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.