combine putIfAbsent and replace with ConcurrentMap

后端 未结 4 2079
长情又很酷
长情又很酷 2021-02-04 03:54

I have a usecase where I have to

  • insert a new value if the key does not exist in the ConcurrentHashMap
  • replace the old value with a new value if the key a
4条回答
  •  情深已故
    2021-02-04 04:35

    You could make it a little shorter with the code below which is equivalent to yours. I have stress tested it a little with thousands of threads accessing it concurrently: it works as expected, with a number of retries (loops) being performed (obviously, you can never prove correctness with testing in the concurrent world).

    public void insertOrReplace(String key, String value) {
        for (;;) {
            String oldValue = concurrentMap.putIfAbsent(key, value);
            if (oldValue == null)
                return;
    
            final String newValue = recalculateNewValue(oldValue, value);
            if (concurrentMap.replace(key, oldValue, newValue))
                return;
        }
    }
    

提交回复
热议问题