Synchronize Java ArrayList

By default, Java ArrayList implementation is not synchronized (it is not thread-safe). This means if multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally.

How to synchronize?

We can achieve thread safety by wrapping the ArrayList using the Collections.synchronizedList method.

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

public class SynchronizedListExample {
    public static void main(String[] args) {
        List<String> list = Collections.synchronizedList(new ArrayList<String>());
        
        list.add("Java");
        list.add("Python");
        list.add("Ruby");
        
        synchronized (list) {
            for (String str : list) {
                System.out.println(str);
            }
        }
    }
}
Important: When iterating over the synchronized list, you must manually synchronize on the returned list to avoid non-deterministic behavior.

Alternative: CopyOnWriteArrayList

Another way to have a thread-safe list is using CopyOnWriteArrayList from java.util.concurrent package. It is a thread-safe variant of ArrayList in which all mutative operations (add, set, and so on) are implemented by making a fresh copy of the underlying array.

import java.util.concurrent.CopyOnWriteArrayList;

CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();
list.add("Java");
list.add("Python");

Frequently Asked Questions

What will I learn here?

This page covers the core concepts and techniques you need to understand the topic and progress confidently to the next lesson.

How should I use this page?

Start with the overview, then follow the section links to deepen your understanding. Use the table of contents on the right to jump to specific sections.

What should I read next?

Use the navigation below to continue to the next lesson or explore related topics.