How to make updating BigDecimal within ConcurrentHashMap thread safe

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

    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?

提交回复
热议问题