How to make updating BigDecimal within ConcurrentHashMap thread safe

前端 未结 4 1141
再見小時候
再見小時候 2020-12-14 03:15

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 multip

4条回答
  •  孤城傲影
    2020-12-14 03:45

    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.

提交回复
热议问题