...
When the addAndPrintIP()
method is invoked on the same object from multiple threads, the output, consisting of varying array lengths, may indicate a race condition between the threads. In other words, the statements in method addAndPrint()
that are responsible for adding an IP address and printing it out are not sequentially consistent.
Noncompliant Code Example (Subclass)
This noncompliant code example extends the base class and synchronizes the addAndPrintIP()
method which is required to be atomic.
Compliant Solution (Synchronized block)
To eliminate the race condition, ensure atomicity by using the underlying list's lock. This can be achieved by including all statements that use the array list within a synchronized block that locks on the list.
Code Block |
---|
|
class |
Code Block |
---|
|
class RaceCollectionSub extends RaceCollection {
publicprivate synchronizedfinal voidList<InetAddress> addAndPrintIP()ips throws UnknownHostException {= Collections.synchronizedList(new ArrayList<InetAddress>());
public void addIPAddress(InetAddress.getLocalHost());
InetAddress[] ia = (InetAddress[]) ips.toArray(new InetAddress[0]); ia) {
synchronized (ips) {
// Validate
Systemips.out.println("Number of IPs: " + ia.length);add(ia);
}
}
}
|
...
...
...
...
...
...
...
...
...
...
...
...
...
(ips) {
addIPAddress(InetAddress.getLocalHost());
ia = (InetAddress[]) ips.toArray(new InetAddress[0]);
System.out.println("Number of IPs: " + ia.length);
}
}
}
|
Wiki Markup |
---|
This technique is also called client-side locking \[[Goetz 06|AA. Java References#Goetz 06]\], because the class holds a lock on an object that presumably might be accessible to other classes. Goetz et al. |
Extension is more fragile than adding code directly to a class, because the implementation of the synchronization policy is now distributed over multiple, separately maintained source files. If the underlying class were to change its synchronization policy by choosing a different lock to guard its state variables, the subclass would subtly and silently break, because it no longer used the right lock to control concurrent access to the base class's state.
Wiki Markup |
---|
Moreover, when a wrapper such as {{Collections.synchronizedList()}} is used (as shown in the previous noncompliant code example), it is unwieldy for a client to determine the type of the class ({{List}}) that is being wrapped. Consequently, it is not directly possible to extend the class \[[Goetz 06|AA. Java References#Goetz 06]\]. |
Compliant Solution (Synchronized block)
To eliminate the race condition, ensure atomicity by using the underlying list's lock. This can be achieved by including all statements that use the array list within a synchronized block that locks on the list.
Code Block |
---|
|
class RaceCollection {
private final List<InetAddress> ips = Collections.synchronizedList(new ArrayList<InetAddress>());
public void addIPAddress(InetAddress ia) {
synchronized (ips) {
// Validate
ips.add(ia);
}
}
public void addAndPrintIP() throws UnknownHostException {
synchronized (ips) {
addIPAddress(InetAddress.getLocalHost());
ia = (InetAddress[]) ips.toArray(new InetAddress[0]);
System.out.println("Number of IPs: " + ia.length);
}
}
}
|
Wiki Markup |
---|
This technique is also called client-side locking \[[Goetz 06|AA. Java References#Goetz 06]\], because the class holds a lock on an object that presumably might be accessible to other classes. Goetz et al. \[[Goetz 06|AA. Java References#Goetz 06]\] caution against misuse of client-side locking: |
If extending a class to add another atomic operation is fragile because it distributes the locking code for a class over multiple classes in an object hierarchy, client-side locking is even more fragile because it entails putting locking code for class C into classes that are totally unrelated to C. Exercise care when using client-side locking on classes that do not commit to their locking strategy.
Wiki Markup |
---|
Although expensive, {{CopyOnWriteArrayList}} and {{CopyOnWriteArraySet}} classes are sometimes used to create copies of the core {{Collection}} so that iterators do not fail with a runtime exception when some data in the {{Collection}} is modified. However, any updates to the {{Collection}} are not immediately visible to other threads. Consequently, their use is limited to boosting performance in code where the writes are fewer (or non-existent) as compared to the reads \[[JavaThreads 04|AA. Java References#JavaThreads 04]\]. In all other cases they must be avoided (see [MSC13-J. Do not modify the underlying collection when an iteration is in progress]). |
Compliant Solution (Composition)
Composition offers more benefits as compared to the previous solution, although at the cost of a slight performance penalty (refer to OBJ07-J. Understand how a superclass can affect a subclass for details on how to implement composition).
Code Block |
---|
|
class CompositeCollection {
private final List<InetAddress> ips;
public CompositeCollection(List<InetAddress> list) {
this.ips = list;
}
public synchronized void addIPAddress(InetAddress ia) {
// Validate
ips.add(ia);
}
public synchronized void addAndPrintIP() throws UnknownHostException {
addIPAddress(InetAddress.getLocalHost());
InetAddress[] ia = (InetAddress[]) ips.toArray(new InetAddress[0]);
System.out.println("Number of IPs: " + ia.length);
}
}
|
caution against misuse of client-side locking: |
If extending a class to add another atomic operation is fragile because it distributes the locking code for a class over multiple classes in an object hierarchy, client-side locking is even more fragile because it entails putting locking code for class C into classes that are totally unrelated to C. Exercise care when using client-side locking on classes that do not commit to their locking strategy.
Wiki Markup |
---|
Although expensive, {{CopyOnWriteArrayList}} and {{CopyOnWriteArraySet}} classes are sometimes used to create copies of the core {{Collection}} so that iterators do not fail with a runtime exception when some data in the {{Collection}} is modified. However, any updates to the {{Collection}} are not immediately visible to other threads. Consequently, their use is limited to boosting performance in code where the writes are fewer (or non-existent) as compared to the reads \[[JavaThreads 04|AA. Java References#JavaThreads 04]\]. In all other cases they must be avoided (see [MSC13-J. Do not modify the underlying collection when an iteration is in progress]). |
Wiki Markup |
---|
This approach allows the {{CompositeCollection}} class to use its own intrinsic lock in a way that is completely independent of the lock of the underlying list class. Moreover, this permits the underlying collection to be thread-unsafe because the {{CompositeCollection}} wrapper prevents direct accesses to its methods by exposing its own synchronized equivalents. This approach also provides consistent locking even when the underlying list is not thread-safe or when it changes its locking policy. \[[Goetz 06|AA. Java References#Goetz 06]\] |
Noncompliant Code Example (synchronizedMap
)
...