...
CON30-J. Ensure that calls to chained methods are atomic describes a specialized case of this guideline.
Noncompliant Code Example (AtomicReference
)
This noncompliant code example wraps BigInteger
objects within thread-safe AtomicReference
objects.
...
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.
Code Block | ||
---|---|---|
| ||
final class Adder { // ... public synchronized void update(BigInteger f, BigInteger s){ first.set(f); second.set(s); } public synchronized BigInteger add() { return first.get().add(second.get()); } } |
Noncompliant Code Example (synchronizedList
)
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
to avoid a ConcurrentModificationException
.
...
Individually, the 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 modify the list before the first thread completes. Consequently, the addressCopy
array may contain more IP addresses then expected.
Compliant Solution (Synchronized Block)
The race condition can be eliminated by synchronizing on the underlying list's lock. This compliant solution encapsulates all references to the array list within synchronized blocks.
...
This code does not violate CON06-J. Do not synchronize on a collection view if the backing collection is accessible, because while it does synchronize on a collection view (the synchronizedList
), the backing collection is inaccessible, and therefore cannot be modified by any code.
Noncompliant Code Example (synchronizedMap
)
Wiki Markup |
---|
This noncompliant code example defines a class {{KeyedCounter}} that 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]\]. |
Code Block | ||
---|---|---|
| ||
final 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 oldValue = (old == null) ? 0 : old.intValue(); if (oldValue == Integer.MAX_VALUE) { throw new ArithmeticException("Out of range"); } map.put( key, oldValue + 1); } public Integer getCount(String key) { return map.get(key); } } |
Compliant Solution (synchronization)
To ensure atomicity, this compliant solution uses an internal private lock object to synchronize the statements of the increment()
and getCount()
methods.
...
To prevent overflow, the caller must ensure that the increment()
method is called no more than Integer.MAX_VALUE
times for any key. See INT00-J. Perform explicit range checking to ensure integer operations do not overflow for more information.
Compliant Solution (ConcurrentHashMap
)
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.
...
Note that methods such as size()
and isEmpty()
are allowed to return an approximate result for performance reasons. Code should not rely on these return values for deriving exact results.
Risk Assessment
Failing to ensure 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.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
CON07 CON03- J | low | probable | medium | P4 | L3 |
Automated Detection
TODO
Related Vulnerabilities
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" |
...