1.

What is an ArrayList? Are they thread-safe? If not then, what are the various ways in which they can be made thread-safe?

Answer»

An ArrayList is a homogenous collection of elements. The elements are placed in contiguous memory locations. Unlike an array which is of fixed SIZE, ArrayList is dynamic in nature i.e. its size automatically grows when new elements get added to it.

It is part of Java’s Collection framework and IMPLEMENTATION of its List interface.

A thread-safe collection is one that operates in the DESIRED manner even when multiple threads are OPERATING on it in parallel. An ArrayList is not threadsafe by default. It means that in a multi-threaded environment with multiple threads adding or removing elements from ArrayList at the same time, extra care needs to be taken to ensure that transactions are atomic in nature and do not interfere with one another. This can be done by synchronizing the ArrayList. There are two ways to achieve this:

  • One is to usesynchronizedList() method from Collections API – This method returns a threadsafe version of the original list. However, when iterating this threadsafe list, we should manually synchronize it as well.
  • Another way is to useCopyOnWriteArrayList. It is a thread-safe variant of ArrayList API and doesn’t require explicit synchronization while traversal. All mutative operations like add, remove, etc are implemented by creating a separate copy of the underlying array.


Discussion

No Comment Found