Reputation: 1289
I have a Concurrent Hash Map where I need to update the value in a loop. Although , the concurrent map itself is thread safe but the add operation is not atomic and hence I need to add the synchronized block. Please correct me if I am wrong here.
The question is if this code can be synchronized more efficiently using locks etc.? I am getting the values from a blocking queue.
Here is the code:
// running in a loop
String i = (String) queue.take();
synchronized(this) {
if(hashmap.containsKey(i)) {
hashmap.put(i, hashmap.get(i) + 1);
} else {
hashmap.put(i, 1);
}
}
Upvotes: 0
Views: 90
Reputation: 32980
You can use ConcurrentHashMap.computeIfAbsent
and AtomicInteger
values to implement your counter map without synchronization on the whole map:
ConcurrentHashMap<String,AtomicInteger> map = new ConcurrentHashMap<>();
String key = ...
map.computeIfAbsent(key, k -> new AtomicInteger()).incrementAndGet();
Upvotes: 3