Thread safe Hash Map?

后端 未结 3 1011
盖世英雄少女心
盖世英雄少女心 2020-12-04 11:04

I am writing an application which will return a HashMap to user. User will get reference to this MAP. On the backend, I will be running some threads which will update the Ma

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-04 12:08

    You are on the right track using ConcurrentHashMap. For each point:

    1. Check out the methods putIfAbsent and replace both are threadsafe and combine checking current state of hashmap and updating it into one atomic operation.
    2. The get method is not synchronized internally but will return the most recent value for the specified key available to it (check the ConcurrentHashMap class Javadoc for discussion).

    The benefit of ConcurrentHashMap over something like Collections.synchronizedMap is the combined methods like putIfAbsent which provide traditional Map get and put logic in an internally synchronized way. Use these methods and do not try to provide your own custom synchronization over ConcurrentHashMap as it will not work. The java.util.concurrent collections are internally synchronized and other threads will not respond to attempts at synchronizing the object (e.g. synchronize(myConcurrentHashMap){} will not block other threads).

提交回复
热议问题