2

How do I prevent a concurrency in Spring transactional?

The situation is two requests in parallel to the method below:

@Transactional
public save() {
    Optional<Example> result = repository.findById(1);
    if(!result.isPresent()) {
        Example exemple = new Exemple();
        exemple.setParam1(1);
        exemple.setParam2(1);
        exemple.setParam3(1);
        exemple.setParam4(1);
        exemple.setParam5(1);
        exemple.setParam6(1);
        exemple.setParam7(1);
        exemple.setParam8(1);
        repository.save(exemple);
    }
}

So, for exemple, the second request passes through the "ifPresent" verification before the first request ends and commit. Causing unexpected behavior and saving the object twice.

Do I need to use the @EnableTransactionManagement? Do I need to use some value in @Transactional?

Victor Soares
  • 757
  • 1
  • 8
  • 34

1 Answers1

0

There is no direct relationship between your problem and the @Transactional behavior. The problem you encountered was the classic issue unsynchronized methods called from a few threads, while @Transactional ensures that all changes in the database occur simultaneously after they have been committed.

The simplest solution is to make the method that calls this save (=a wrapper method [Because of the AOP nature, it must be in another class otherwise the @Transactional won't take affect]) synchronized. For more information, please see this answer.

yoni
  • 1,164
  • 2
  • 13
  • 29