Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: removed another NCE, tx to new guideline

...

Code Block
bgColor#ccccff
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());
       InetAddress[] 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:

...

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

...