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
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.