Synchronized Collections
In Chapter 23, we discuss multithreading. The collections in the collections framework are unsynchronized by default, so they can operate efficiently when multithreading is not required. Because they are unsynchronized, however, concurrent access to a Collection by multiple threads could cause indeterminate results or fatal errors. To prevent potential threading problems, synchronization wrappers are used for collections that might be accessed by multiple threads. A wrapper object receives method calls, adds thread synchronization (to prevent concurrent access to the collection) and delegates the calls to the wrapped collection object. The Collections API provides a set of static methods for wrapping collections as synchronized versions. Method headers for the synchronization wrappers are listed in Fig. 19.22. Details about these methods are available at java.sun.com/j2se/5.0/docs/api/java/util/Collections.html. All these methods take a generic type and return a synchronized view of the generic type. For example, the following code creates a synchronized List (list2) that stores String objects:
List< String > list1 = new ArrayList< String >(); List< String > list2 = Collections.synchronizedList( list1 );
public static method headers |
---|
< T > Collection< T > synchronizedCollection( Collection< T > c ) |
< T > List< T > synchronizedList( List< T > aList ) |
< T > Set< T > synchronizedSet( Set< T > s ) |
< T > SortedSet< T > synchronizedSortedSet( SortedSet< T > s ) |
< K, V > Map< K, V > synchronizedMap( Map< K, V > m ) |
< K, V > SortedMap< K, V > synchronizedSortedMap( SortedMap< K, V > m ) |