...
Code Block | ||
---|---|---|
| ||
final class IPHolder { private final List<InetAddress> ips = Collections.synchronizedList(new ArrayList<InetAddress>()); public void addAndPrintIPAddresses(InetAddress address) { synchronized (ips) { ips.add(address); InetAddress[] addressCopy = (InetAddress[]) ips.toArray(new InetAddress[0]); // Iterate through array addressCopy ... } } } |
This technique is also called client-side locking \[ [Goetz 2006|AA. References#Goetz 06]\] 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 rule [LCK11-J. Avoid client-side locking when using classes that do not commit to their locking strategy] for more information. Wiki Markup
This code does not violate rule LCK04-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
result), the backing collection is inaccessible and consequently cannot be modified by any code.
...
Noncompliant Code Example (synchronizedMap()
)
...
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|AA. 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); } } |
...
The previous compliant solution is safe for multithreaded use but does not scale because of excessive synchronization, which can lead to decreased performance.unmigrated-wiki-markup
The {{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|AA. References#Lee 09]\].
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 of an impact on performance as the previous compliant solution.
Code Block | ||
---|---|---|
| ||
final class KeyedCounter { private final ConcurrentMap<String, AtomicInteger> map = new ConcurrentHashMap<String, AtomicInteger>(); private final Object lock = new Object(); public void increment(String key) { AtomicInteger value = new AtomicInteger(); AtomicInteger old = map.putIfAbsent(key, value); if (old != null) { value = old; } synchronized (lock) { 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 ... } |
...
According to Section 5.2.1., "ConcurrentHashMap" of the work of Goetz and colleagues \[ [Goetz 2006|AA. References#Goetz 06]\]:
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.
...
CWE-362. Concurrent execution using shared resource with improper synchronization ("race condition") | |
| CWE-366. Race condition within a thread |
| CWE-662. Improper synchronization |
Bibliography
[API 2006] |
| |||
Section 4.4.1, Client-side Locking | ||||
| Section 5.2.1, ConcurrentHashMap | |||
Section 8.2, Synchronization and Collection Classes | ||||
[Lee 2009] | Map & Compound Operation | |||
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="b6dbb9e7-87a1-4596-b810-d93076f2d738"><ac:plain-text-body><![CDATA[ | [[API 2006 | AA. References#API 06]] |
| ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="4ec93a73-53fb-43ab-9203-524d25f84e24"><ac:plain-text-body><![CDATA[ | [[Goetz 2006 | AA. References#Goetz 06]] | Section 4.4.1, Client-side Locking | ]]></ac:plain-text-body></ac:structured-macro> |
| Section 5.2.1, ConcurrentHashMap | |||
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="db85ee6b-eb8a-41e8-b6b6-c6b8a7da850e"><ac:plain-text-body><![CDATA[ | [[JavaThreads 2004 | AA. References#JavaThreads 04]] | Section 8.2, Synchronization and Collection Classes | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="88defc5e-5ad9-4271-b03b-656b323e1174"><ac:plain-text-body><![CDATA[ | [[Lee 2009 | AA. References#Lee 09]] | Map & Compound Operation | ]]></ac:plain-text-body></ac:structured-macro> |
...