Suppose, I have concurrentHashMap code such as below:
ConcurrentHashMap<Integer,Integer> balances = new ConcurrentHashMap<>();
public void add(int accountId, int amountToAdd){
int currentBalance = balances.get(accountId);
balances.put(accountId, currentBalance + amountToAdd);
}
This add
method is called from multiple threads, there can be attempt to update the amount of the same accountId at same time.
How to ensure the currentBalance doesn't change between the get
and the put
? Because from my understanding, if thread preempts after doing get
, and meanwhile some other thread updates the balance, put
will perform update with stale balance.