combine putIfAbsent and replace with ConcurrentMap

后端 未结 4 2078
长情又很酷
长情又很酷 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:40

    Your method seems thread safe. If you do not require the performance benefits of ConcurrentHashMap, consider using a regular HashMap instead and synchronize all access to it. Your method is similar to AtomicInteger.getAndSet(int), so it should be fine. I doubt there is an easier way to do this unless you're looking for a library call to do the work for you.

提交回复
热议问题