InterviewSolution
| 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:
|
|