Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Programmers sometimes assume that using a thread-safe Collection does not require explicit synchronization which is a misleading thought. It follows that using a thread-safe Collection by itself does not ensure program correctness unless special care is taken to ensure that the client performs all related and independently atomic operations, as one atomic operation.

This guideline applies to all uses of Collection classes including the thread-safe Hashtable class. Enumerations of the objects of a Collection and iterators also require explicit synchronization on the Collection object or any single lock object.

Noncompliant Code Example

...

Code Block
bgColor#FFCCCC
class RaceCollection implements Runnable {
  private List<InetAddress> ips = Collections.synchronizedList(new ArrayList<InetAddress>());
  
  public void addIPAddress(InetAddress ia) {
    // Validate
    ips.add(ia);
  }
  
  public void rundoSomething() {
    trythrows UnknownHostException {
      addIPAddress(InetAddress.getLocalHost());
      InetAddressInetAddress[] ia = (InetAddress[]) ips.toArray(new InetAddress[0]);      
      System.out.println("Number of IPs: " + ia.length);     
    } catch (UnknownHostException e) { /* Forward to handler */ }     		
  }
  
  public static void main(String[] args) {
    RaceCollection rc = new RaceCollection();
    for(int i = 0; i < 2; i++) {
      new Thread(rc).start();
    }	  	  
  }
}

The operations within a thread's run() method are non-atomic. That is, it is possible for the first thread to operate on data that it does not expect. This noncompliant code's output, consisting of varying array lengths, indicates a race condition between threads. In other words, the statements that are responsible for adding an IP address and printing it out are not sequentially consistent.

Compliant Solution

Wiki Markup
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. This technique is also called client-side locking \[[Goetz 06|AA. Java References#Goetz 06]\]. 

}

When the doSomething() method is invoked on the same object from multiple threads, the output, consisting of varying array lengths, indicates a race condition between the threads. In other words, the statements that are responsible for adding an IP address and printing it out are not sequentially consistent. Also note that the operations within a thread's run() method are non-atomic.

Noncompliant Code Example

This noncompliant code example extends the base class and synchronizes on the doSomething() method which is required to be atomic.

Code Block
bgColor#FFCCCC

class RaceCollectionSub extends RaceCollection {
  public synchronized void doSomething() throws UnknownHostException {
    addIPAddress(InetAddress.getLocalHost());
    InetAddress[] ia = (InetAddress[]) ips.toArray(new InetAddress[0]);      
    System.out.println("Number of IPs: " + ia.length);     
  }
}

Wiki Markup
However, this is not recommended because it goes against the spirit of limiting class extension ([OBJ05-J. Limit the extensibility of non-final classes and methods to only trusted subclasses]). Moreover, Goetz et al. \[[Goetz 06|AA. Java References#Goetz 06]\] cite other reasons:

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

Noncompliant Code Example

This noncompliant code example appears to use synchronization when defining the doSomething() method, however, it acquires an intrinsic lock instead of the lock of the List object. This means that another thread may modify the value of the List instance when the doSomething() method is executing.

Code Block
bgColor#FFCCCC

class Helper {
  private List<InetAddress> ips = Collections.synchronizedList(new ArrayList<InetAddress>());
  
  public synchronized
Code Block
bgColor#ccccff

public void addIPAddress(InetAddress ia) { 
  synchronized(ips) { // Also synchronize this method
    // Validate
    ips.add(ia);
  }
}

  public synchronized void rundoSomething() {
throws  tryUnknownHostException {
    synchronized(ips) {
      addIPAddress(InetAddress.getLocalHost());
InetAddress[] ia;   
    ia = (InetAddress[]) ips.toArray(new InetAddress[0]);     
    System.out.println("Number of IPs: " + ia.length); 
  }
}

Compliant Solution

Wiki Markup
To eliminate the race condition, ensure atomicity 

...

by using the underlying list's 

...

This form of synchronization is preferable over method synchronization for performance reasons. The advice suggested by this guideline applies to all uses of Collection classes including the thread-safe Hashtable class. Enumerations of the objects of a Collection and iterators also require explicit synchronization on the Collection object or any single lock object.

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.    

Compliant Solution

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
bgColor#ccccff

class CompositeCollection implements Runnable {
  private List<InetAddress> ips;
 
  public CompositeCollection(List<InetAddress> list) {
    this.ips = list;
  }
  
  public synchronized void addIPAddress(InetAddress ia) {
    // Validate
    ips.add(ia);
  }

  public void run() {
    try {
      InetAddress[] ia;   
      ia = (InetAddress[]) ips.toArray(new InetAddress[0]);     
      System.out.println("Number of IPs: " + ia.length); 
    } catch (UnknownHostException e) { /* Forward to handler */ }     		
  }
}

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

Wiki Markup
Yet another method is to extend the base class and synchronize on the method that is desired to be atomic, however, it is not recommended because it goes against the spirit of limiting class extension ([OBJ05-J. Limit the extensibility of non-final classes and methods to only trusted subclasses]). Moreover, Goetz et al. \[[Goetz 06|AA. Java References#Goetz 06]\] cite other reasons:

...

lock. This can be achieved by including all statements that use the array list within a synchronized block that locks on the list. This technique is also called client-side locking \[[Goetz 06|AA. Java References#Goetz 06]\]. 

Code Block
bgColor#ccccff

public void addIPAddress(InetAddress ia) { 
  synchronized(ips) { // Also synchronize this method
    // Validate
    ips.add(ia);
  }
}

public void doSomething() throws UnknownHostException {
  synchronized(ips) {
    addIPAddress(InetAddress.getLocalHost());
    ia = (InetAddress[]) ips.toArray(new InetAddress[0]);           
    System.out.println("Number of IPs: " + ia.length); 
  }
}

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

Compliant Solution

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
bgColor#ccccff

class CompositeCollection {
  private List<InetAddress> ips;
 
  public CompositeCollection(List<InetAddress> list) {
    this.ips = list;
  }
  
  public synchronized void addIPAddress(InetAddress ia) {
    // Validate
    ips.add(ia);
  }

  public synchronized void doSomething() throws UnknownHostException {
    InetAddress[] ia;   
    ia = (InetAddress[]) ips.toArray(new InetAddress[0]);     
    System.out.println("Number of IPs: " + ia.length); 
  }
}

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

Wiki Markup
This noncompliant code example defines a thread-unsafe {{KeyedCounter}} class. Even though the {{HashMap}} field is synchronized, the overall {{increment}} operation is not atomic. \[[Lee 09|AA. Java References#Lee 09]\]   

...