Thread-safety guarantees that no two threads can simultaneously access or modify some shared data. However, if two or more operations need to be performed safely, it becomes necessary to enforce atomicity. It is possible for two threads to read some shared value, independently perform operations on it and induce a race condition while storing the final result. For example, programmers sometimes assume that a thread-safe Collection
does not require explicit synchronization which is a misleading thought. It follows that using a thread-safe Collection
by itself may not ensure program correctness.
Noncompliant Code Example
This noncompliant code example is comprised of an ArrayList
collection which is non-thread-safe by default. There is, however, a way around this drawback. Most thread-unsafe classes have a synchronized thread-safe version, for example, Collections.synchronizedList
is a good substitute for ArrayList
and Collections.synchronizedMap
is a good alternative to HashMap
. The atomicity pitfall described in the coming lines, remains to be addressed even when the particular Collection
offers thread-safety benefits.
...
Code Block | ||
---|---|---|
| ||
class RaceCollection implements Runnable { private List<InetAddress> ips = Collections.synchronizedList(new ArrayList<InetAddress>()); public void addIPAddress(InetAddress ia) { synchronized(ips) { ips.add(ia); } } public void removeIPAddress(InetAddress ia) { synchronized(ips) { ips.remove(ia); } } public void nonAtomic() throws InterruptedException { InetAddress[] ia; synchronized(ips) { ia = (InetAddress[]) ips.toArray(new InetAddress[0]); } // This statement should be in the synchronized block above System.out.println("Number of IPs: " + ia.length); } public void run() { try { addIPAddress(InetAddress.getLocalHost()); nonAtomic(); } catch (UnknownHostException e) { /* Forward to handler */ } catch (InterruptedException e) { /* Forward to handler */ } } public static void main(String[] args) { RaceCollection rc1 = new RaceCollection(); for(int i = 0; i < 2; i++) { new Thread(rc1).start(); } } } |
Compliant Solution
Wiki Markup |
---|
To eliminate the race condition, ensure atomicity. This can be achieved by including all statements that use the array list within the synchronized block. This technique is also called client-side locking. \[[Goetz 06|AA. Java References#Goetz 06]\] |
...
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. These however, suffer from the {{toArray}} dilemma (operating on stale data) described earlier in this rule. 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. |
Compliant Solution
Wiki Markup |
---|
Composition offers more benefits as compared to the previous solution, although at the cost of a slight performance penalty (refer to [OBJ07-J. Understand how a superclass can affect a subclass] for details on how to implement composition). This allows the {{CompositeCollection}} class to use its own intrinsic lock in a way that is completely independent of the lock of the underlying list class. This provides consistent locking even when the underlying list is not thread-safe or when it changes its locking policy. \[[Goetz 06|AA. Java References#Goetz 06]\] |
...
Extension is more fragile than adding code directly to a class, because the implementation of the synchronization policy is now distributed over multiple, separately maintained source files. If the underlying class were to change its synchronization policy by choosing a different lock to guard its state variables, the subclass would subtly and silently break, because it no longer used the right lock to control concurrent access to the base class's state.
Noncompliant Code Example
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); } } |
Compliant Solution
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); } } |
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: |
...
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(String key) { AtomicInteger value = map.get(key); return (value == null) ? null : value.get(); } } |
Risk Assessment
Non-atomic code can induce race conditions and affect program correctness.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
CON06 CON07- J | low | probable | medium | P4 | L3 |
Automated Detection
TODO
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Wiki Markup |
---|
\[[API 06|AA. Java References#API 06]\] Class Vector, Class WeakReference \[[JavaThreads 04|AA. Java References#JavaThreads 04]\] 8.2 "Synchronization and Collection Classes" \[[Goetz 06|AA. Java References#Goetz 06]\] 4.4.1. Client-side Locking, 4.4.2. Composition and 5.2.1. ConcurrentHashMap \[[Lee 09|AA. Java References#Lee 09]\] "Map & Compound Operation" |
...