Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Java concurrency guidelines.pdf
Скачиваний:
16
Добавлен:
23.05.2015
Размер:
1.35 Mб
Скачать

VNA03-J

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 than expected.

2.4.4Compliant 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.

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] 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 guideline “LCK11-J. Avoid client-side locking when using classes that do not commit to their locking strategy” on page 86 for more information.

This code does not violate guideline “LCK04-J. Do not synchronize on a collection view if the backing collection is accessible” on page 57 because, while it does synchronize on a collection view (the synchronizedList), the backing collection is inaccessible and therefore cannot be modified by any code.

2.4.5Noncompliant 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 non-atomic [Lee 2009].

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);

CMU/SEI-2010-TR-015 | 25

VNA03-J

}

public Integer getCount(String key) { return map.get(key);

}

}

2.4.6Compliant Solution (Synchronization)

To ensure atomicity, this compliant solution uses an internal private lock object to synchronize the statements of the increment() and getCount() methods.

final class KeyedCounter {

private final Map<String, Integer> map = new HashMap<String, Integer>(); private final Object lock = new Object();

public void increment(String key) { synchronized (lock) {

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) { synchronized (lock) {

return map.get(key);

}

}

}

This compliant solution does not use Collections.synchronizedMap() because locking on the unsynchronized map provides sufficient thread-safety for this application. Guideline “LCK04-J. Do not synchronize on a collection view if the backing collection is accessible” on page 57 provides more information about synchronizing on synchronizedMap objects.

2.4.7Compliant Solution (ConcurrentHashMap)

The previous compliant solution is safe for multithreaded use, but it does not scale well because of excessive synchronization, which can lead to contention and deadlock.

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].

final class KeyedCounter {

private final ConcurrentMap<String, AtomicInteger> map =

CMU/SEI-2010-TR-015 | 26

VNA03-J

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 ...

}

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 ConcurrentHashMap 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.

Note that methods such as ConcurrentHashMap.size() and ConcurrentHashMap.isEmpty() are allowed to return an approximate result for performance reasons. Code should not rely on these return values for deriving exact results.

CMU/SEI-2010-TR-015 | 27

VNA03-J

2.4.8Risk 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.

Guideline

Severity

Likelihood

Remediation Cost

Priority

Level

 

 

 

 

 

 

VNA03- J

low

probable

medium

P4

L3

2.4.9References

[Goetz 2006]

Section 4.4.1, “Client-side Locking”

 

Section 5.2.1, “ConcurrentHashMap”

[Lee 2009]

“Map & Compound Operation”

[Oaks 2004]

Section 8.2, “Synchronization and Collection Classes”

[Sun 2009c]

 

CMU/SEI-2010-TR-015 | 28

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]