...
| Wiki Markup |
|---|
This noncompliant code example defines a thread-unsafe {{KeyedCounter}} class. Even though the {{HashMap}} field is synchronized, the overall {{increment}} operation is not atomic. \[[Lee 09|AA. Java References#Lee 09]\] |
| Code Block | ||
|---|---|---|
| ||
public class KeyedCounter {
private Map<String,Integer> map =
Collections.synchronizedMap(new HashMap<String,Integer>());
public void increment(String key) {
Integer old = map.get(key);
int value = (old == null) ? 1 : old.intValue()+1;
map.put(key, value);
}
public Integer getCount(String key) {
return map.get(key);
}
}
|
...