Search code examples
javamultithreadingspring-bootjava-8transactions

Best way to impletent Java multithreading to prevent transaction rollback


I have an List which contains say 4 DTOs. I am performing some processes on each of the DTOs present in my list. If suppose for one the DTO, any exception comes then all the transactions are rolled back (even if the process is success for other 3 DTOs).

My code looks like this :

@Transactional
public void processEvent(List<MyObject> myList){
   myList.forEach(dto -> process(dto));
}

public void process(MyObject dto){
//some code which calls another class marked as @Transactional
// and save the data processed to database
}

I want to perform these processes for each DTO on a sepearte thread such that exception encountered in one thread does not rollbacks transaction for all the DTOs. Also is there a way to process these DTOs one by one on different threads so that data consistency is maintained ?


Solution

  • Simply move the transactional to the method called with the dto, plus I am not sure if it is needed a transaction for dto. This looks as a controller which should not have any transactional annotaions. In the service once you change the dto to entity and are ready to save it you may put the anotation. Furthermore if you are simply calling the repository's save method you do not need to be in transaction as save method has the annotation in the repository.

    public void processEvent(List<MyObject> myList){
       myList.forEach(dto -> process(dto));
    }
    
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void process(MyObject dto){
    //some code which calls another class marked as @Transactional
    // and save the data processed to database
    }
    

    And one last advice do not put @Transactional on classes, except if they have the readOnly parameter set to true. Then you can put @Transactional on the methods that perform any CRUD operations.