dcsimg

How do I synchronize a collection?

John Zukowski

With the Collections Framework, the new implementations are all unsynchronized by default. If you need synchronized access, you must synchronize things yourself. The Collections class offers a wrapper method for each of the six core collection interfaces that add synchronization to an arbitrary collections implementation. To ensure thread-safety, direct access to the original backing collection must be avoided.

For example, the following will synchronize an arbitrary List and lose the original reference so you can't access it directly:

List list = ...;
list = Collections.synchronizedList(list);