A consistent locking policy guarantees that multiple threads cannot simultaneously access or modify shared data. When two or more operations must be performed as a single atomic operation, a consistent locking policy must be implemented using either intrinsic synchronization or
java.util.concurrent utilities. In the absence of such a policy, the code is susceptible to race conditions.
When presented with a set of operations, where each is guaranteed to be atomic, it is tempting to assume that a single operation consisting of individually atomic operations is guaranteed to be collectively atomic without additional locking. Similarly, programmers might incorrectly assume that use of a thread-safe
Collection is sufficient to preserve an invariant that involves the collection's elements without additional synchronization. A thread-safe class can only guarantee atomicity of its individual methods. A grouping of calls to such methods requires additional synchronization for the group.
Consider, for example, a scenario in which the standard thread-safe API lacks a single method both to find a particular person's record in a
Hashtable and to update that person's payroll information. In such cases, the two method invocations must be performed atomically.
Enumerations and iterators also require either explicit synchronization on the collection object (client-side locking) or use of a private final lock object.
Compound operations on shared variables are also non-atomic (see VNA02-J. Ensure that compound operations on shared variables are atomic for more information).
VNA04-J. Ensure that calls to chained methods are atomic describes a specialized case of this rule.
Noncompliant Code Example (
This noncompliant code example wraps references to
BigInteger objects within thread-safe
AtomicReference is an object reference that can be updated atomically. However, operations that combine more than one atomic reference are non-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
add() methods synchronized to guarantee atomicity:
Noncompliant Code Example (
This noncompliant code example uses a
java.util.ArrayList<E> collection, which is not thread-safe. However, the example uses
Collections.synchronizedList as a synchronization wrapper for the
ArrayList. It subsequently uses an array, rather than an iterator, to iterate over the
ArrayList to avoid a
toArray() collection methods are atomic. However, when called in succession (as shown in the
addAndPrintIPAddresses() method), there is no guarantee that the combined operation is atomic. The
addAndPrintIPAddresses() method contains a race condition 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 than 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 technique is also called client-side locking [Goetz 2006] because the class holds a lock on an object that might be accessible to other classes. Client-side locking is not always an appropriate strategy (see LCK11-J. Avoid client-side locking when using classes that do not commit to their locking strategy for more information).
This code does not violate LCK04-J. Do not synchronize on a collection view if the backing collection is accessible because, although it synchronizes on a collection view (the
synchronizedList result), the backing collection is inaccessible and consequently cannot be modified by any code.
Note that this compliant solution does not actually use the synchronization offered by
Collections.synchronizedList(). If no other code in this solution used it, it could be eliminated.
Noncompliant Code Example (
This noncompliant code example defines the
KeyedCounter class that is not thread-safe. Although the
HashMap is wrapped in a
synchronizedMap(), the overall increment operation is not atomic [Lee 2009].
Compliant Solution (Synchronization)
This compliant solution ensures atomicity by using an internal private lock object to synchronize the statements of the
This compliant solution avoids using
Collections.synchronizedMap() because locking on the unsynchronized map provides sufficient thread-safety for this application. LCK04-J. Do not synchronize on a collection view if the backing collection is accessible provides more information about synchronizing on
Compliant Solution (
The previous compliant solution is safe for multithreaded use but does not scale because of excessive synchronization, which can lead to decreased performance.
ConcurrentHashMap class used in this compliant solution provides several utility methods for performing atomic operations and is often a good choice for algorithms that must scale [Lee 2009].
Note that this compliant solution still requires synchronization, because without it, the test to prevent overflow and the increment will not happen atomically, so two threads calling
increment() can still cause overflow. The synchronization block is smaller and does not include the lookup or addition of new values, so it has less impact on performance than the previous compliant solution.
According to Section 5.2.1., "
ConcurrentHashMap," of the work of Goetz and colleagues [Goetz 2006]:
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
ConcurrentHashMapare 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.
Note that methods such as
ConcurrentHashMap.isEmpty() are allowed to return an approximate result for performance reasons. Code should avoid relying on these return values when exact results are required.
Failure to ensure the atomicity of two or more operations that must be performed as a single atomic operation can result in race conditions in multithreaded applications.
Some static analysis tools are capable of detecting violations of this rule.
|JAVA.CONCURRENCY.VOLATILE||Useless volatile Modifier (Java)|
|Make the get method for a field synchronized if the set method is synchronized|
Access related Atomic variables in a synchronized block
Section 4.4.1, "Client-side Locking"
Section 8.2, Synchronization and Collection Classes
Map & Compound Operation