Making Collections thread-safe

Let's discuss how collections can be made thread-safe.

We'll cover the following

Most of the collections such as ArrayList, LinkedList, HashSet, HashMap, etc., are not thread-safe. If two parallel threads modify any of these collections parallelly, the user can get stale data or ConcurrentModificationException.

We can use thread-safe alternatives such as CopyOnWriteArrayList, ConcurrentHashMap, etc., but what if we don’t want to use these alternatives? What if we have already created an ArrayList, and now we want to make it thread-safe.

The Collections class provides us with the following methods that can be used to make our existing collection thread-safe.

  1. synchronizedCollection(Collection<T> c)
  2. synchronizedList(List<T> list)
  3. synchronizedMap(Map<K,V> m)
  4. synchronizedSet(Set<T> s)
  5. synchronizedSortedMap(SortedMap<K,V> m)
  6. synchronizedSortedSet(SortedSet<T> s)

Get hands-on with 1400+ tech skills courses.