The key difference between the historical collection classes
and the new implementations within the Collections Framework is
the new classes are not thread-safe. The designers took this approach to allow you to use synchronization only when you need it, making everything work much faster. If, however, you are using a
collection in a multi-threaded environment, where multiple
threads can modify the collection simultaneously, the
modifications need to be synchronized. The Collections
class provides for the ability to wrap existing collections
into synchronized ones with another set of six methods:
Collection synchronizedCollection(Collection
collection)
List synchronizedList(List list)
Map synchronizedMap(Map map)
Set synchronizedSet(Set set)
SortedMap synchronizedSortedMap(SortedMap map)
SortedSet synchronizedSortedSet(SortedSet set)
Synchronize the
collection immediately after creating it. You also must not retain a reference to the original collection, or else
you can access the collection unsynchronized. The simplest way to
make sure you don't retain a reference is never to create one:
Set set = Collection.synchronizedSet(new HashSet());
Making a collection unmodifiable also makes a collection
thread-safe, as the collection can't be modified. This avoids the
synchronization overhead.