Java concurrent list

In Java, you can create a thread-safe list by using the Collections.synchronizedList method or by using data structures from the java.util.concurrent package. Here are two common ways to create a thread-safe list.

Using Collections.synchronizedList

This method wraps an existing list with synchronized (thread-safe) methods. Here's an example:

import java.util.Collections;
import java.util.List;
import java.util.ArrayList;

public class Example {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        List<String> synchronizedList = Collections.synchronizedList(list);

        // Now synchronizedList is thread-safe
        // However, you should synchronize on the list when iterating over it
        synchronized (synchronizedList) {
            for (String item : synchronizedList) {
                // Do something with item
            }
        }
    }
}

It's important to note that iteration over a Collections.synchronizedList must be manually synchronized to avoid concurrent modification exceptions.

Using java.util.concurrent

The java.util.concurrent package includes several thread-safe collection classes. The CopyOnWriteArrayList is one such class that is useful when the number of read operations vastly outnumber the write operations:

import java.util.concurrent.CopyOnWriteArrayList;
import java.util.List;

public class Example {
    public static void main(String[] args) {
        List<String> threadSafeList = new CopyOnWriteArrayList<>();

        // Now threadSafeList is thread-safe and you can iterate over it without
        // additional synchronization, because it uses a copy-on-write mechanism
        for (String item : threadSafeList) {
            // Do something with item
        }
    }
}

CopyOnWriteArrayList makes a fresh copy of the underlying array with every write operation (such as add or set). Thus, it can be quite expensive in terms of memory and performance when write operations are frequent.

Choosing between Collections.synchronizedList and CopyOnWriteArrayList depends on your specific requirements regarding read and write operations, as well as the importance of memory efficiency and performance.

For scenarios where you need concurrent modifications and high performance, consider using alternatives like the ConcurrentLinkedQueue or ConcurrentLinkedDeque, which provide thread-safe operations without locking, due to their non-blocking algorithms. However, these are not strictly list implementations (they implement the Queue and Deque interfaces, respectively) but may be suitable depending on the use case.

Last updated