...
Wiki Markup |
---|
This compliant solution declares the {{increment()}} method as {{synchronized}} to ensure atomicity. \[[Lee 09|AA. Java References#Lee 09]\]. |
Code Block |
---|
|
public class KeyedCounter {
private Map<String,Integer> map = new HashMap<String,Integer>();
public synchronized void increment(String key) {
Integer old = map.get(key);
int value = (old == null) ? 1 : old.intValue()+1;
map.put(key, value);
}
public synchronized Integer getCount(String key) {
return map.get(key);
}
}
|
Also, note that this would be a violation of a previously discussed noncompliant code example if the field map
were to refer to a Collections.synchronizedMap
object. This compliant solution uses the intrinsic lock of the class for all purposes.
Compliant Solution
Wiki Markup |
---|
The previous compliant solution does not scale very well because a class with several {{synchronized}} methods is a potential bottleneck as far as acquiring locks is concerned and may further lead to contention or deadlock. The class {{ConcurrentHashMap}}, through a more preferable approach, provides several utility methods to perform atomic operations and is used in this compliant solution \[[Lee 09|AA. Java References#Lee 09]\]. According to Goetz et al. \[[Goetz 06|AA. Java References#Goetz 06]\] section 5.2.1. ConcurrentHashMap: |
...