Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#FFCCCC
final class KeyedCounter {
  private final Map<String, Integer> map =
    Collections.synchronizedMap(new HashMap<String, Integer>());

  public void increment(String key) {
    Integer old = map.get(key);
    int oldValue = (old == null) ? 0 : old.intValue();
    if (oldValue == Integer.MAX_VALUE) {    
      throw new ArithmeticException("Out of range");
    }
    map.put( key, valueoldValue + 1);
  }

  public Integer getCount(String key) {
    return map.get(key);
  }
}

...

Code Block
bgColor#ccccff
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 oldValue = (old == null) ? 0 : old.intValue();
      if (oldValue == Integer.MAX_VALUE) {    
        throw new ArithmeticException("Out of range");
      }
      map.put(key, valueoldValue + 1);
    }
  }

  public Integer getCount(String key) {
    synchronized (lock) {
      return map.get(key);
    }
  }
}

...

CON06-J. Do not synchronize on a collection view if the backing collection is accessible      11. Concurrency (CON)      

o