How to make updating BigDecimal within ConcurrentHashMap thread safe

前端 未结 4 1139
再見小時候
再見小時候 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:44

    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.

提交回复
热议问题