...
| Code Block | ||
|---|---|---|
| ||
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 | ||
|---|---|---|
| ||
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