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.
synchronizedCollection(Collection<T> c)
synchronizedList(List<T> list)
synchronizedMap(Map<K,V> m)
synchronizedSet(Set<T> s)
synchronizedSortedMap(SortedMap<K,V> m)
synchronizedSortedSet(SortedSet<T> s)
Get hands-on with 1400+ tech skills courses.