Reputation: 1539
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
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>.
Upvotes: 43
Views: 60534
Reputation: 29629
You are on the right track using ConcurrentHashMap
. For each point:
putIfAbsent
and replace
both are threadsafe and combine checking current state of hashmap and updating it into one atomic operation.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).
Upvotes: 58
Reputation: 1171
ConcurrentHashMap was designed and implemented to avoid any issues with the scenarios you describe. You have nothing to worry about.
A hash table supporting full concurrency of retrievals and adjustable expected concurrency for updates.updates.
Upvotes: 1
Reputation: 7288
Side Note:
You might want to look into the lock free hash table implementation by Cliff Click, it's part of the Highly Scalable Java library
(Here's a Google Talk by Cliff Click about this lock free hash.)
Upvotes: 8