Versions Compared

Key

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

...

Code Block
bgColor#ccccff
synchronized(ips) {
  ia = (InetAddress[]) ips.toArray(new InetAddress[0]);           
  System.out.println("Number of IPs: " + ia.length); 
}

Wiki MarkupNote that this advice applies to all {{Collection}} classes including the thread-safe hash tables. 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 mayare alsosometimes be 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. These however, suffers from the {{toArray}} dilemma (operating on stale data) described earlier in this rule. Therefore 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.    

Risk Assessment

Non-atomic code can induce race conditions and affect program correctness.

...