If you do not synchronize the entire block of code that performs the update, it will not work as you expect.
A synchronized card simply ensures that nothing unpleasant happens if you call, say, put several times at the same time. He does not guarantee that
myMap.put("username", myMap.get("username") + 1);
performed atomically.
You must truly synchronize the entire block that performs the update. Either using Semaphore , or using the synchronized . For instance:
final Object lock = new Object(); ... synchronized(lock) { if (!myMap.containsKey(username)) myMap.put(username, 0); myMap.put(username, myMap.get(username) + 1); if (myMap.get(username) >= THRESHOLD) {
source share