Next page | Contents page |

Synchronising collections and maps

Synchronisation wrappers

The basic collections are unsynchronised. Therefore you may need to wrap them to obtain synchronised views:

	Map map = Collections.synchronizedMap (new HashMap ());

There are 6 synchronisation wrappers:

	synchronizedCollection (), synchronizedList (), synchronizedMap (),
	synchronizedSet (), synchronizedSortedMap (), synchronizedSortedSet ()

They wrap the interfaces rather than the classes, so only the methods implemented from the relevant interface are then synchronised, not any additional methods.

There are other useful wrappers in class Collections, to make unmodifiable (read-only) views and checked views (type safe: throw ClassCastException). 6 flavours of each wrapper again.

java.util.concurrent

(New in Java 5.)

The "Concurrent" prefix on some class names in this package indicates several differences from similar synchronised classes. Eg, java.util.Collections.synchronizedMap (new HashMap ()) is synchronised but ConcurrentHashMap is concurrent.

A concurrent collection is thread-safe, but not governed by a single exclusion lock. Eg, ConcurrentHashMap safely permits any number of concurrent reads as well as a tunable number of concurrent writes.

Most concurrent Collection implementations also differ from the usual java.util conventions in that their Iterators provide weakly consistent rather than fail-fast* traversal. A weakly consistent iterator is thread-safe, but does not necessarily freeze the collection while iterating, so it may (or may not) reflect any updates since the iterator was created.

* Throwing ConcurrentModificationException

Synchronise or not?

Sun's advice:

People are nervous about synchronisation because it is not easy to set up to test for the rare occurences of conflicts between threads.

Next page | Contents page |