Search code examples
javamultithreadingconcurrencyconcurrenthashmap

More efficient multi threading possible?


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);      
    }
}

Solution

  • 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();