Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

spring - @Transaction how to get updated via multiple threads

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?

question from:https://stackoverflow.com/questions/65929121/transaction-how-to-get-updated-via-multiple-threads

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...