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,
synchronizedSortedSet, synchronizedList, synchronizedMap, or
synchronizedSortedMap. These factory methods return wrappers whose methods are fully
synchronized and so are safe to use from multiple threads. For example, the following code creates a new
HashMap that can be safely modified concurrently:
Map<String, String> unsyncMap =
new HashMap<String, String>();
Map<String, String> syncMap =
Collections.synchronizedMap(unsyncMap);
The map referred to by unsyncMap is a full, but unsynchronized, implementation of the Map interface. The
Map returned by synchronizedMap has all relevant methods synchronized, passing all calls through to the
wrapped map (that is, to unsyncMap). Modifications made through either map are visible to the otherthere is
really only one map with two different views: the unwrapped, unsynchronized view referenced by
unsyncMap, and the wrapping, synchronized view referenced by syncMap:
Because the underlying collection is unsynchronized, you must be very careful what you do with
unsyncMap. The safest alternative is to drop the reference and do all work through syncMap. If you do not,
you must be sure that you carefully control concurrency. The wrapper synchronizes on itself, so you could use
syncMap to synchronize access on the collection and then use unsyncMap safely inside such code:
// add a lot of elements but grab the lock only once
synchronized (syncMap) {
for (int i = 0; i < keys.length; i++)
unsyncMap.put(keys[i], values[i]);
}
Iterators returned by synchronized wrappers are not synchronized but must be manually synchronized in a
similar manner when needed:
synchronized (syncMap) {
System.out.println("--- map contents:");
for (String key : syncMap.keySet())
System.out.println(key + ": " + syncMap.get(key));