...
Code Block |
---|
|
class RaceCollection {
private final List<InetAddress> ips = Collections.synchronizedList(new ArrayList<InetAddress>());
public void addIPAddress(InetAddress ia) {
// Validate
ips.add(ia);
}
public void addAndPrintIP() throws UnknownHostException {
addIPAddress(InetAddress.getLocalHost());
InetAddress[] ia = (InetAddress[]) ips.toArray(new InetAddress[0]);
System.out.println("Number of IPs: " + ia.length);
}
}
|
When the addAndPrintIP()
method is invoked on the same object from multiple threads, the output, consisting of varying array lengths, indicates a race condition between the threads. In other words, the statements in method addAndPrint()
that are responsible for adding an IP address and printing it out are not sequentially consistent. Also note that Likewise, the operations within a thread's run()
method are non-atomicnonatomic.
Noncompliant Code Example (Subclass)
This noncompliant code example extends the base class and synchronizes on the addAndPrintIP()
method which is required to be atomic.
...
Code Block |
---|
|
class Helper {
public final List<InetAddress> ips = Collections.synchronizedList(new ArrayList<InetAddress>());
public synchronized void addIPAddress(InetAddress ia) {
// Validate
ips.add(ia);
}
public synchronized void addAndPrintIP() throws UnknownHostException {
addIPAddress(InetAddress.getLocalHost());
InetAddress[] ia = (InetAddress[]) ips.toArray(new InetAddress[0]);
System.out.println("Number of IPs: " + ia.length);
}
}
|
This noncompliant code example also violates OBJ00-J. Declare data members private. It does not violate CON02-J. Always synchronize on the appropriate object because ips
is declared as final
and consequently, the lock object cannot be changed by another thread.
Compliant Solution (Synchronized block)
...
Code Block |
---|
|
public void addIPAddress(InetAddress ia) {
synchronized(ips) { // Also synchronize this method
// 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);
}
}
|
...
Wiki Markup |
---|
Although expensive, {{CopyOnWriteArrayList}} and {{CopyOnWriteArraySet}} classes are sometimes used to create copies of the core {{Collection}} so that iterators do not fail with a runtime exception when some data in the {{Collection}} is modified. However, any updates to the {{Collection}} are not immediately visible to other threads. Consequently, their use is limited to boosting performance in code where the writes are fewer (or non-existent) as compared to the reads \[[JavaThreads 04|AA. Java References#JavaThreads 04]\]. In all other cases they must be avoided (see [MSC13-J. Do not modify the underlying collection when an iteration is in progress]). |
Compliant Solution (Composition)
...
Code Block |
---|
|
class CompositeCollection {
private final List<InetAddress> ips;
public CompositeCollection(List<InetAddress> list) {
this.ips = list;
}
public synchronized void addIPAddress(InetAddress ia) {
// Validate
ips.add(ia);
}
public synchronized void addAndPrintIP() throws UnknownHostException {
addIPAddress(InetAddress.getLocalHost());
InetAddress[] ia = (InetAddress[]) ips.toArray(new InetAddress[0]);
System.out.println("Number of IPs: " + ia.length);
}
}
|
...
Noncompliant Code Example (synchronizedMap
)
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 final 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);
}
}
|
Compliant Solution (
...
synchronized method)
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 final 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 (ConcurrentHashMap
)
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: |
ConcurrentHashMap
, along with the other concurrent collections, further improve on the synchronized collection classes by providing iterators that do not throw ConcurrentModificationException
, as a result eliminating the need to lock the collection during iteration. The iterators returned by ConcurrentHashMap
are weakly consistent instead of fail-fast. A weakly consistent iterator can tolerate concurrent modification, traverses elements as they existed when the iterator was constructed, and may (but is not guaranteed to) reflect modifications to the collection after the construction of the iterator.
Code Block |
---|
|
public class KeyedCounter {
private final ConcurrentMap<String, AtomicInteger> map =
new ConcurrentHashMap<String, AtomicInteger>();
public void increment(String key) {
AtomicInteger value = new AtomicInteger(0);
AtomicInteger old = map.putIfAbsent(key, value);
if (old != null) {
value = old;
}
value.incrementAndGet(); // Increment the value atomically
}
public Integer getCount |
Code Block |
---|
|
public class KeyedCounter {
private final ConcurrentMap<String, AtomicInteger> map =
new ConcurrentHashMap<String, AtomicInteger>();
public void increment(String key) {
AtomicInteger value = new AtomicInteger(0map.get(key);
AtomicIntegerreturn old(value = map.putIfAbsent(key, value= null) ? null : value.get();
if (old != null) {
value = old;
}
value.incrementAndGet(); // Increment the value atomically
}
public Integer getCount(String key) {
AtomicInteger value = map.get(key);
return (value == null) ? null : value.get();
}
}
}
}
|
Wiki Markup |
---|
According to Goetz et al. \[[Goetz 06|AA. Java References#Goetz 06]\] section 5.2.1. ConcurrentHashMap: |
ConcurrentHashMap
, along with the other concurrent collections, further improve on the synchronized collection classes by providing iterators that do not throw ConcurrentModificationException
, as a result eliminating the need to lock the collection during iteration. The iterators returned by ConcurrentHashMap
are weakly consistent instead of fail-fast. A weakly consistent iterator can tolerate concurrent modification, traverses elements as they existed when the iterator was constructed, and may (but is not guaranteed to) reflect modifications to the collection after the construction of the iterator.
Risk Assessment
Non-atomic code can induce race conditions and affect program correctness.
...