Java Reference
In-Depth Information
21.11. Synchronized Wrappers and Concurrent Collections
All the collection implementations provided in java.util are unsynchron-
ized (except the legacy collections you will soon see). You must ensure
any necessary synchronization for concurrent access from multiple
threads. You can do this explicitly with synchronized methods or state-
ments, or algorithmically by designing your code to use a given collection
from only one thread. These techniques are how collections are often
naturally usedas local variables in methods or as private fields of classes
with synchronized code.
Thread-safety for collection classes themselves takes two main forms:
lock-based synchronization to ensure that concurrent access is pre-
cluded, and the use of sophisticated data structures that allow (to varying
degrees) truly concurrent use of a collection. The former is provided
through the synchronized wrappers, while the latter are provided in the
java.util.concurrent subpackage.
21.11.1. The Synchronized Wrappers
A synchronized wrapper passes through all method calls to the wrapped
collection after adding any necessary synchronization. You can get a
synchronized wrapper for a collection from one of the following static
methods of Collections : synchronizedCollection , synchronizedSet , synchron-
izedSortedSet , synchronizedList , synchronizedMap , or synchronizedSortedMap .
These factory methods return wrappers whose methods are fully syn-
chronized and so are safe to use from multiple threads. For example, the
following code creates a new HashMap that can be safely modified concur-
rently:
Map<String, String> unsyncMap =
new HashMap<String, String>();
Map<String, String> syncMap =
Collections.synchronizedMap(unsyncMap);
 
Search WWH ::




Custom Search