Java Reference
In-Depth Information
Cloning a collection and iterating over the clone may cause problems. The clone() methods
for ArrayList and HashSet produce a shallow copy: They merely create a new collection
that refers to the same objects as the original. Relying on a clone will fail if other threads can
change the underlying objects in a way that interferes with your method. But in some cases,
this risk is small. For example, if you want to display a list of machine names, it may be
unlikely or inconsequential whether the names change while your method iterates over a clone
of the list. The advantage of cloning the list before traversing it is speed. Cloning a collection
is often much faster than waiting for another method to finish operating on the collection's
contents.
CHALLENGE 28.5
What changes would you make to the ShowConcurrentMutex program to let
the primary thread iterate over a clone of the collection, allowing the second thread
to work without waiting for access to the collection?
Summary
The intent of the I TERATOR pattern is to let a client access the elements of a collection
sequentially. The collection classes in the Java class libraries offer rich support for operating
on collections, including support for iteration. These iterators usually require a client to cast
the returned objects to the appropriate type. You can strengthen your contract with clients by
creating type-specific collections with type-specific iterators.
If you create a new type of collection, you will often want to create an iterator to go with it.
Domain-specific composites are a common example of a new collection type. You can design
a fairly generic iterator for composites that you may be able to apply against a variety of
composite hierarchies.
When you instantiate an iterator, you should consider whether the collection can change while
you are iterating over it. There is usually not much chance of this in a single-threaded
application. In a multithreaded application, you first have to ensure that access to a collection
is synchronized. The Java class libraries provide good support for this, but that support does
not guarantee safe iteration. To safely iterate in a multithreaded application, you can
synchronize on the monitor of a mutex object. You can either block out all access while
iterating or block access briefly while you make a clone of the collection. With a proper
design, you can provide thread safety and type safety to the clients of your iterator code.
Search WWH ::




Custom Search