Versions Compared

Key

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

...

This noncompliant code example uses a java.util.ArrayList<E> collection, which is not thread-safe. However, Collections.synchronizedList is used as a synchronization wrapper for ArrayList. An array, rather than an iterator, is used to iterate over Arraylist ArrayList to avoid a ConcurrentModificationException.

...

Individually, the add() and toArray() collection methods are atomic. However, when they are called in succession (for example in the addAndPrintIPAddresses() method), there are no guarantees that the combined operation is atomic. A race condition exists in the 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 then than expected.

Compliant Solution (Synchronized Block)

...