What happens when an annotated @Transactional method hits multiple instances in parallel?

Please correct me if I am mistaken somewhere.

I had a problem when my transaction is not saved in the database, and there are some races that spin the data. The application falls in parallel with several instances. I used @Transactional, which, as I know, should do a transaction with the database, and the transaction is committed when the method returns.

The question is whether hitting it through several instances saves this transaction in each case, or does it not cope with the situation, and the data will be corrupted due to races?

Is there a solution for this condition?

+4
source share
2 answers

@Transactionalnot associated with synchronization. It just ensures that your thread succeeds or fails. Each hit has its own flow and its own success or failure.

I assume that you are worried about using shared data.

For example. If you have a class Foothat looks like this:

public class Foo {
    private static boolean flag = true;

    @Transactional
    public void doSomething() {
        flag = false;
    }
}

In this case, it does not matter that you have many instances Foo, because they all use the same one flag.

Another scenario would be if you have one instance Foo(very common if you use something like Spring) and you have data that has been changed for that instance. You can look at the same example Fooand just remove staticfrom flag:

public class Foo {
    private boolean flag = true;

    @Transactional
    public void doSomething() {
        flag = false;
    }
}

- . @Transactional.

+2

, , :

  • .
  • . , @Transactional .
  • , . . SELECT * FROM MYTABLE FOR UPDATE;.
  • , . . UPDATE MYTABLE SET A = A + 1; .
  • , 3, , commit .
  • , .
+2

Source: https://habr.com/ru/post/1527129/


All Articles