Java Concurrency Incrementing a Value

后端 未结 3 477
眼角桃花
眼角桃花 2021-01-03 07:38

I have been reading about volatile and synchronized in Java but have been scratching my head in confusion. I am hoping someone can help me clear up

3条回答
  •  北海茫月
    2021-01-03 08:05

    The answer is of course to use AtomicInteger, not int.

    And if you use a ConcurrentHashMap, you need to use its special thread-safe method putIfAbsent().

    Here's a javadoc excerpt from that method:

    This is equivalent to

    if (!map.containsKey(key))
        return map.put(key, value);
    else
        return map.get(key);
    

    except that the action is performed atomically.

    private ConcurrentMap map = new ConcurrentHashMap();
    
    AtomicInteger value = map.get("value");
    if (value == null) {
        map.putIfAbsent("value", new AtomicInteger());
        value = map.get("value");
    }
    value.incrementAndGet();
    

    Note how you don't have to put the new value back.

    If you make that change to your code, it should all work just fine.

提交回复
热议问题