...
Code Block | ||
---|---|---|
| ||
class RaceCollection { // ...private final List<InetAddress> ips = Collections.synchronizedList(new ArrayList<InetAddress>()); public void addIPAddress(InetAddress ia) { synchronized (ips) { // Validate ips.add(ia); } } public void addAndPrintIP() throws UnknownHostException { synchronized (ips) { addIPAddress(InetAddress.getLocalHost()); ia = (InetAddress[]) ips.toArray(new InetAddress[0]); System.out.println("Number of IPs: " + ia.length); } } } |
...
Compliant Solution (synchronized blocks)
...
This compliant solution uses a private object lock to synchronize the method bodies of the {{increment()
}} and {{getCount
}} methods, to ensure atomicity \[[Lee 09|AA. Java References#Lee 09]\]. For more information on private object locks, see [CON04-J. Use the private lock object idiom instead of the Class object's intrinsic locking mechanism].
Code Block | ||
---|---|---|
| ||
public 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);
}
}
}
|
...