Java Language Concurrent Collections Thread-safe Collections


By default, the various Collection types are not thread-safe.

However, it's fairly easy to make a collection thread-safe.

List<String> threadSafeList = Collections.synchronizedList(new ArrayList<String>());
Set<String> threadSafeSet = Collections.synchronizedSet(new HashSet<String>());
Map<String, String> threadSafeMap = Collections.synchronizedMap(new HashMap<String, String>());

When you make a thread-safe collection, you should never access it through the original collection, only through the thread-safe wrapper.

Java SE 5

Starting in Java 5, java.util.collections has several new thread-safe collections that don't need the various Collections.synchronized methods.

List<String> threadSafeList = new CopyOnWriteArrayList<String>();
Set<String> threadSafeSet = new ConcurrentHashSet<String>();
Map<String, String> threadSafeMap = new ConcurrentHashMap<String, String>();