我创建了一个实体用户,它有整数属性交易配额。 我需要根据交易配额的价值更新交易配额。
如果大于0,则需要减少,否则其价值需要保留。
这是我的算法
- Retrive user entity from database.
- Check transaction quota, if transaction quota greater than 0, reduce it by one.
- Persist the changed user entity.
In above case, when concurrent request comes if two thread retrieves same user entity and then both threads read same transaction quota value and if it is greater than 0 then both reduces by 1 and updates the user entity.
ex. 前 ex
ThreadA: val = e.getTxnQuota(); val = 5
ThreadB: val = e.getTxnQuota(); val = 5
ThreadA: e.setTxnQuota(val- 1); val = 4
ThreadB: e.setTxnQuota(val- 1); val =4
ThreadA: eDao.save(e);
ThreadB: eDao.save(e);
在以上情况下,节省的价值是4,而不是3。
那么,我是否有什么办法可以创造出一种原子交易,我可以在其中检查交易配额并更新用户实体?