Home > database >  using CompletableFuture inside spring @Transactional
using CompletableFuture inside spring @Transactional

Time:12-05

I am working with an api which is marked as transactional. It is using completable future inside that to keep things async. So api looks like :

@Transactional
public Response executeJob (Request request){

   //check if job is already in progress using db read

   //if not -> create new job put it in progress and start

   //if previously failed -> update job status to in progress and restart
  
   //update job status in DB

   //submit job to completable future -> preforms lots of db reads and writes

   //return Response details

}

Problem : We are getting duplicate record in case lots of users trigger the request simultaneously.

I tried searching the internet but could not understand how will transactional and completable future work here. I mean the transaction will end once the response is returned or once completable future completes.

CodePudding user response:

Key observation : I tried a couple of cases myself using a dummy api. In case of completable future always a new transaction is initiated for new thread. whether it is annotated by transaction or not, if it is called by a transactional method it will create a new transaction for this thread. If we use results returned by this completable future, it could also be that the transaction which initially started got completed, now if we try to persist something which needs to be in a transaction, it may fail by no active transaction present. Please let me know if this seems to be incorrect anywhere or if some more clarity is needed

  • Related