Sobes.tech
Junior — Middle

What thread-safe equivalent of ArrayList is presented in the java.util.concurrent library?

sobes.tech AI

Answer from AI

In the java.util.concurrent library, the thread-safe equivalent of ArrayList is the CopyOnWriteArrayList class.

This class implements the List interface and ensures safety when accessed concurrently from multiple threads by copying the internal array during each modification operation (such as adding or removing an element). This makes reading very fast and non-blocking, but write operations are more expensive.

Example usage:

import java.util.concurrent.CopyOnWriteArrayList;

CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
list.add("First element");
list.add("Second element");

for (String item : list) {
    System.out.println(item);
}

This approach is suitable for scenarios where read operations significantly outnumber write operations.

What thread-safe equivalent of ArrayList is presented… - sobes.tech