Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: i would not say that the integer overflow check was ommited for brevity, but rather that the burden has been shifted to the caller. i'm wondering how/where the key is initialized to 0?

...

Code Block
bgColor#FFCCCC
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.

...