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 Map.
What I have done so far?
I have made all the backend threads so share a common channel to update the MAP. So at backend I am sure that concurrent write operation will not be an issue.
Issues I am having
- If user tries to update the MAP and simultaneously MAP is being updated at backend –> Concurrent write operation problem.
- If use tries to read something from MAP and simultaneously MAP is being updated at backend –> concurrent READ and WRITE Operation problem.
Untill now I have not face any such issue, but i m afraid that i may face in future. Please give sugesstions.
I am using ConcurrentHashMap<String, String>.
You are on the right track using
ConcurrentHashMap. For each point:putIfAbsentandreplaceboth are threadsafe and combine checking current state of hashmap and updating it into one atomic operation.The benefit of
ConcurrentHashMapover something likeCollections.synchronizedMapis the combined methods likeputIfAbsentwhich provide traditional Mapgetandputlogic in an internally synchronized way. Use these methods and do not try to provide your own custom synchronization overConcurrentHashMapas it will not work. Thejava.util.concurrentcollections are internally synchronized and other threads will not respond to attempts at synchronizing the object (e.g.synchronize(myConcurrentHashMap){}will not block other threads).