0

I have been facing this issue for a while.

@Service
public class SomeService{

   @Autowired
   private Repo repo;

   @Transactional
   public void update(int id){
     repo.findById(id).ifPresent(entity -> entity.setName(entity.getName() + "-name"));
   }

}

My problem is that - often times same id is passed by 2 different threads to update the entity. I see only the last update in the entity.

That is -

entity.getName() by default will return some. the expected result is - some-name-name but what i see in the end is some-name.

The problem seems to be findbyId is executed at the same time by 2 different threads and leave that entity in this state.

How to handle this?

RamPrakash
  • 2,218
  • 3
  • 25
  • 54

1 Answers1

1

You should use optimistic locking with retry to make sure both updates end up committing.

Have a look at this question: Spring Optimistic Locking:How to retry transactional method till commit is successful

The key is to use Spring Retry and capture the optimistic locking exception.

codependent
  • 23,193
  • 31
  • 166
  • 308