Search code examples
javamultithreadingthread-safetyjava.util.concurrentconcurrenthashmap

I'm trying to increment value for ConcurrentHashMap


All with multi-threaded programming and without Guava. My problem is the same as this one, but i want to solve it without break;. I have already read this topic, but still didn't resolve problem, I newborn in multi-threaded, so perhaps the solution is here, but I can not see it.

I'm trying to count words. If this word already met, just increment value, if is not, just put new node into map with key word and value 1.

This my code, and it is wrong. I want to avoid any loops.

String word = m.group();
if(wordMap.putIfAbsent(word, 1) == null){
    Integer old;
    while (!wordMap.replace(word, old = wordMap.get(word), old + 1));
}

Solution

  • The merge-Method is what you're most likely looking for:

    String word = m.group();
    wordMap.merge(word, 1, Integer::sum);