Java Reference
In-Depth Information
Chapter 5. Building Blocks
The last chapter explored several techniques for constructing thread-safe classes, including
delegating thread safety to existing thread-safe classes. Where practical, delegation is one
of the most effective strategies for creating thread-safe classes: just let existing thread-safe
classes manage all the state.
The platform libraries include a rich set of concurrent building blocks, such as thread-safe
collections and a variety of synchronizers that can coordinate the control flow of cooperat-
ing threads. This chapter covers the most useful concurrent building blocks, especially those
introduced in Java 5.0 and Java 6, and some patterns for using them to structure concurrent
applications.
5.1. Synchronized Collections
The synchronized collection classes include Vector and Hashtable , part of the original
JDK, as well as their cousins added in JDK 1.2, the synchronized wrapper classes created
by the Collections.synchronizedXxx factory methods. These classes achieve thread
safety by encapsulating their state and synchronizing every public method so that only one
thread at a time can access the collection state.
5.1.1. Problems with Synchronized Collections
The synchronized collections are thread-safe, but you may sometimes need to use additional
client-side locking to guard compound actions. Common compound actions on collections in-
clude iteration (repeatedly fetch elements until the collection is exhausted), navigation (find
the next element after this one according to some order), and conditional operations such as
put-if-absent (check if a Map has a mapping for key K , and if not, add the mapping ( K , V )).
With a synchronized collection, these compound actions are still technically thread-safe even
without client-side locking, but they may not behave as you might expect when other threads
can concurrently modify the collection.
Listing 5.1 shows two methods that operate on a Vector , getLast and delete-Last ,
both of which are check-then-act sequences. Each calls size to determine the size of the array
and uses the resulting value to retrieve or remove the last element.
Listing 5.1. Compound Actions on a Vector that may Produce Confusing Results.
Search WWH ::




Custom Search