...
Code Block | ||
---|---|---|
| ||
final class KeyedCounter { private final Map<String, Integer> map = new HashMap<String, Integer>(); private final Object lock = new Object(); public void increment(String key) { synchronized (lock) { Integer old = map.get(key); int value = (old == null) ? 1 : old.intValue() + 1; map.put(key, value); } } public Integer getCount(String key) { synchronized (lock) { return map.get(key); } } } |
The integer overflow check that should be used before incrementing has been omitted for brevity. To prevent overflowBecause there is not check for integer overflow following the addition, the caller must ensure that the increment()
method is called no more than Integer.MAX_VALUE
times for any key. Refer to INT00-J. Perform explicit range checking to ensure integer operations do not overflow for more information.
...