ssinganamalla
ssinganamalla

Reputation: 1280

Spring - @Transactional with ScheduledExecutorService - What happens in background?

I want to know what actually happens when you annotate a method with @Transactional with ScheduledExecutorService?

Assume that the methodA is called externally. Am I correct in assuming that when methodA is called, someDao.methodDao() joins in a transaction and scheduleMethodB() returns immediately.

Later after 2 seconds, the scheduler calls the methodB(). What would this hold in this case? Would it hold the TransactionProxy and execute methodB in a separate transaction? If not, then how would we able to achieve this.

I am aware that @Transactional is based on proxies so is methodB call a self invocation under scheduler.

Note: Since this mechanism is based on proxies, only 'external' method calls coming in through the proxy will be intercepted. This means that 'self-invocation', i.e. a method within the target object calling some other method of the target object, won't lead to an actual transaction at runtime even if the invoked method is marked with @Transactional!

public class ServiceABImpl implements ServiceAB {

    @Autowired
    private ScheduledExecutorService scheduledExecutorService;

    @Transactional
    public void methodA() {

        //do some work in a transaction.
        someDao.methodDao();

        //schedule a methodB
        scheduleMethodB();


    }

    public void scheduleMethodB() {

        scheduledExecutorService.schedule(() -> {
                    this.methodB();
                    return "";

                },
                2,
                TimeUnit.SECONDS);
    }

    @Transactional
    public void methodB() {


    }

}

Upvotes: 2

Views: 614

Answers (1)

Basanth Roy
Basanth Roy

Reputation: 6500

Since the class is not annotated with @Transactional, the decision of whether an invoked method participates in the transaction of the parent invokee method depends on whether you annotate the invoked methods also with @Transactional and what propagation level you configure it with I think. So for example

@Transactional(propagation=Propagation.REQUIRED)

Upvotes: 1

Related Questions