A consistent locking policy guarantees that multiple threads cannot simultaneously access or modify shared data. If two or more operations need to be performed as a single atomic operation, it is necessary to implement a consistent locking policy by must be implemented using either using intrinsic synchronization or the java.util.concurrent
utilities. In the absence of such a policy, the code is susceptible to race conditions.
Given an invariant involving multiple objects, a programmer may incorrectly assume that individually atomic operations require no additional locking; however, this is not the case. Similarly, programmers may incorrectly assume that using a thread-safe Collection
does not require explicit synchronization to preserve an invariant that involves the collection's elements. A thread-safe class can only guarantee atomicity of its individual methods. A grouping of calls to such methods requires additional synchronization.
...
Compound operations on shared variables are also non-atomic. See For more information, see CON01-J. Ensure that compound operations on shared variables are atomic for more information.
CON30-J. Do not use method chaining implementations in a multithreaded environment describes a specialized case of this guideline.
...
An AtomicReference
is an object reference that can be updated atomically. However, operations that combine more than one atomic reference are not atomic. In this noncompliant code example, one thread may call update()
while a second thread may call add()
. This might cause the add()
method to add the new value of first
to the old value of second
, yielding an erroneous result.
Compliant Solution (
...
Method Synchronization)
This compliant solution declares the update()
and add()
methods as synchronized
to guarantee atomicity.
...
This noncompliant code example uses a java.util.ArrayList<E>
collection, which is not thread-safe. However, the Collections.synchronizedList
is used as a synchronization wrapper for ArrayList
. An array, rather than an iterator, is used to iterate over Arraylist
instead of an iterator to avoid a ConcurrentModificationException
.
Code Block | ||
---|---|---|
| ||
final class IPHolder { private final List<InetAddress> ips = Collections.synchronizedList(new ArrayList<InetAddress>()); public void addAndPrintIPAddresses(InetAddress address) { ips.add(address); InetAddress[] addressCopy = (InetAddress[]) ips.toArray(new InetAddress[0]); // Iterate through array addressCopy ... } } |
Individually, the collection methods add()
and toArray()
collection methods are atomic. However, when they are called in succession , (for example in the addAndPrintIPAddresses()
method), there are no guarantees that the combined operation is atomic. A race condition exists in the addAndPrintIPAddresses()
method that allows one thread to add to the list , and a second thread to race in and also modify the list before the first thread completes. Consequently, the addressCopy
array may contain more IP addresses then expected.
...
Wiki Markup |
---|
This noncompliant code example defines a class {{KeyedCounter}} whichthat is not thread-safe. Although the {{HashMap}} is wrapped in a {{synchronizedMap}}, the overall increment operation is not atomic \[[Lee 09|AA. Java References#Lee 09]\]. |
...
This compliant solution does not use Collections.synchronizedMap()
because locking on the unsynchronized map provides sufficient thread-safety for this application. The guideline CON06-J. Do not synchronize on a collection view if the backing collection is accessible provides more information about synchronizing on synchronizedMap
objects.
To prevent overflow, the caller must ensure that the increment()
method is called no more than Integer.MAX_VALUE
times for any key. Refer to See INT00-J. Perform explicit range checking to ensure integer operations do not overflow for more information.
...
The previous compliant solution is safe for multithreaded use, however, it does not scale well because of excessive synchronization, which can lead to contention and deadlock.
...
Code Block | ||
---|---|---|
| ||
final class KeyedCounter { private final ConcurrentMap<String, AtomicInteger> map = new ConcurrentHashMap<String, AtomicInteger>(); public void increment(String key) { AtomicInteger value = new AtomicInteger(); AtomicInteger old = map.putIfAbsent(key, value); if (old != null) { value = old; } if (value.get() == Integer.MAX_VALUE) { throw new ArithmeticException("Out of range"); } value.incrementAndGet(); // Increment the value atomically } public Integer getCount(String key) { AtomicInteger value = map.get(key); return (value == null) ? null : value.get(); } // Other accessors ... } |
Wiki Markup |
---|
According to Section 5.2.1., "ConcurrentHashMap" of the work of Goetz etand al.colleagues \[[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 throwConcurrentModificationException
, as a result eliminating the need to lock the collection during iteration. The iterators returned byConcurrentHashMap
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
Failing to ensure that the atomicity of two or more operations that need to be performed as a single atomic operation can result in race conditions in multithreaded applications.
...
TODO
Related Vulnerabilities
Search for Any vulnerabilities resulting from the violation of this rule are listed on the CERT website.
References
Wiki Markup |
---|
\[[API 06|AA. Java References#API 06]\] \[[JavaThreads 04|AA. Java References#JavaThreads 04]\] Section 8.2, "Synchronization and Collection Classes" \[[Goetz 06|AA. Java References#Goetz 06]\] Section 4.4.1, "Client-side Locking,", Section 5.2.1, "ConcurrentHashMap" \[[Lee 09|AA. Java References#Lee 09]\] "Map & Compound Operation" |
...