简体   繁体   中英

How to make updating BigDecimal within ConcurrentHashMap thread safe

I am making an application that takes a bunch of journal entries and calculate sum.

Is below way of doing it is thread/concurrency safe when there are multiple threads calling the addToSum() method. I want to ensure that each call updates the total properly.

If it is not safe, please explain what do I have to do to ensure thread safety.

Do I need to synchronize the get/put or is there a better way?

private ConcurrentHashMap<String, BigDecimal> sumByAccount;

public void addToSum(String account, BigDecimal amount){
    BigDecimal newSum = sumByAccount.get(account).add(amount);
    sumByAccount.put(account, newSum);
}

Thanks so much!

Update:

Thanks everyone for the answer, I already get that the code above is not thread-safe .

Thanks Vint for suggesting the AtomicReference as an alternative to synchronize . I was using AtomicInteger to hold integer sums before and I was wondering if there are something like that for BigDecimal.

Is the a definitive conclusion on the pro and con of the two?

You can use synchronized like the others suggested but if want a minimally blocking solution you can try AtomicReference as a store for the BigDecimal

ConcurrentHashMap<String,AtomicReference<BigDecimal>> map;

public void addToSum(String account, BigDecimal amount) {
    AtomicReference<BigDecimal> newSum = map.get(account);
    for (;;) {
       BigDecimal oldVal = newSum.get();
       if (newSum.compareAndSet(oldVal, oldVal.add(amount)))
            return;
    }
}

Edit - I'll explain this more:

An AtomicReference uses CAS to atomically assigns a single reference. The loop says this.

If the current field stored in AtomicReference == oldVal [their location in memory, not their value] then replace the value of the field stored in AtomicReference with oldVal.add(amount) . Now, any time after the for-loop you invoke newSum.get() it will have the BigDecimal object that has been added to.

You want to use a loop here because it is possible two threads are trying to add to the same AtomicReference. It can happen that one thread succeeds and another thread fails, if that happens just try again with the new added value.

With moderate thread contention this would be a faster implementation, with high contention you are better off using synchronized

That is not safe, because threads A and B might both call sumByAccount.get(account) at the same time (more or less), so neither one will see the result of the other's add(amount) . That is, things might happen in this sequence:

  • thread A calls sumByAccount.get("accountX") and gets (for example) 10.0.
  • thread B calls sumByAccount.get("accountX") and gets the same value that thread A did: 10.0.
  • thread A sets its newSum to (say) 10.0 + 2.0 = 12.0.
  • thread B sets its newSum to (say) 10.0 + 5.0 = 15.0.
  • thread A calls sumByAccount.put("accountX", 12.0) .
  • thread B calls sumByAccount.put("accountX", 15.0) , overwriting what thread A did.

One way to fix this is to put synchronized on your addToSum method, or to wrap its contents in synchronized(this) or synchronized(sumByAccount) . Another way, since the above sequence of events only happens if two threads are updating the same account at the same time, might be to synchronize externally based on some sort of Account object. Without seeing the rest of your program logic, I can't be sure.

Your solution is not thread safe. The reason is that it is possible for a sum to be missed since the operation to put is separate from the operation to get (so the new value you are putting into the map could miss a sum that is being added at the same time).

The safest way to do what you want to do is to synchronize your method.

Yes, you need to synchronize since otherwise you can have two threads each getting the same value (for the same key), say A and thread 1 add B to it and thread 2 adds C to it and store it back. The result now will not be A+B+C, but A+B or A+C.

What you need to do is lock on something that is common to the additions. Synchronizing on get/put will not help, unless you do

synchronize {
    get
    add
    put
}

but if you do that then you will prevent threads from updating values even if it is for different keys. You want to synchronize on the account. However, synchronizing on the string seems unsafe as it could lead to deadlocks (you don't know what else locks the string). Can you create an account object instead and use that for locking?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM