Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: moved a comment for array iteration outside the synchronized block (open call) and added a descriptive line

...

Code Block
bgColor#ccccff
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 ...
    }
  }
}

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 might be accessible to other classes. Client-side locking is not always an appropriate strategy; see [CON34-J. Avoid client-side locking when using classes that do not commit to their locking strategy] for more information. 

The addressCopy array holds a copy of the IP addresses and can be safely iterated outside the synchronized block. This code does not violate CON11-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), the backing collection is inaccessible, and therefore cannot be modified by any code.

...