Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: reverted some more wrt int overflow

...

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);
    }
  }
}

Note that while this code is thread-unsafe, it at least prevents integer overflow when incrementing the map values, as mandated by The integer overflow check that should be used before incrementing has been omitted for brevity. To prevent overflow, 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.

Compliant Solution (synchronized blocks)

...