Home > OS >  @Async and @Transactional
@Async and @Transactional

Time:03-03

Question about @Transactional working in @Async working

This is a code sketch for an example:

@Async
@Transactional
 public void data(List<Pass> pass) {
        //code
        for(City city : city) {
            for(Dep dep: city.getDeps()) {
                //code
                setXor(user, xor);
                //code
            }
        }
    }


@Transactional
public void setXor(User user, Xor xor) {
        //code
        user.setXor(xor);
    }

The question is, how will this work, does @Transactional extend from the data method to the setXor method (if you put an annotation on the data method, then maybe you don’t need to put it on setXor? And it will automatically switch to this method)

Also a question about @Async, will setXor work on a new thread along with Async? That is, there will be a main thread, a new one is created, which includes the data method, and since the data method called another method, it will be executed on the same thread as the data method, there will be no third thread. Or vice versa and the setXor method is executed in the main thread?

CodePudding user response:

Spring doesn't create transactions for calls in the same class so the setXor will be executed in the same Transaction as data no matter if you annotate it with transactional or not.

I think also setXor and data will be executed in one Thread other than the main.

CodePudding user response:

As per Spring Transaction Documentation

All code within a transaction scope runs in that transaction. However, you can specify the behavior if a transactional method is run when a transaction context already exists. For example, code can continue running in the existing transaction (the common case), or the existing transaction can be suspended and a new transaction created.

@Transactional commonly works with thread-bound transactions managed by PlatformTransactionManager, exposing a transaction to all data access operations within the current execution thread. Note: This does not propagate to newly started threads within the method.

@Transactional is powered by Aspect-Oriented Programming. Therefore, processing occurs when a bean is called from another bean. In the example above, the method is called from the same class so that no proxies can be applied.

When a method without @Transactional is called within a transaction block, the parent transaction will continue to exist for the new method. It will use the same connection from the parent method (method with @Transactional) and any exception caused in the called method (method without @Transactional) will cause the transaction to rollback as configured in the transaction definition.

  • Related