0
0
JavaHow-ToBeginner · 3 min read

How to Synchronize ArrayList in Java: Simple Guide

To synchronize an ArrayList in Java, wrap it with Collections.synchronizedList() which returns a thread-safe list. This ensures safe access when multiple threads modify the list concurrently.
📐

Syntax

Use Collections.synchronizedList() to wrap your ArrayList. This method returns a synchronized (thread-safe) list backed by the specified list.

  • List<Type> syncList = Collections.synchronizedList(new ArrayList<>());
  • This synchronized list handles internal locking for thread safety.
java
List<Type> syncList = Collections.synchronizedList(new ArrayList<>());
💻

Example

This example shows how to create a synchronized ArrayList and safely add elements from multiple threads.

java
import java.util.*;

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

        Runnable addTask = () -> {
            for (int i = 0; i < 5; i++) {
                list.add(Thread.currentThread().getName() + "-" + i);
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        };

        Thread t1 = new Thread(addTask, "Thread1");
        Thread t2 = new Thread(addTask, "Thread2");

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        synchronized (list) {
            for (String s : list) {
                System.out.println(s);
            }
        }
    }
}
Output
Thread1-0 Thread1-1 Thread1-2 Thread1-3 Thread1-4 Thread2-0 Thread2-1 Thread2-2 Thread2-3 Thread2-4
⚠️

Common Pitfalls

Simply wrapping an ArrayList with Collections.synchronizedList() does not make iteration thread-safe by itself. You must manually synchronize on the list object when iterating to avoid ConcurrentModificationException.

Wrong way (no synchronization during iteration):

for (String s : syncList) {
    System.out.println(s);
}

Right way (synchronize on the list during iteration):

synchronized(syncList) {
    for (String s : syncList) {
        System.out.println(s);
    }
}
📊

Quick Reference

MethodDescription
Collections.synchronizedList(List list)Wraps a list to make it thread-safe.
synchronized(list) { ... }Manually synchronize when iterating over the synchronized list.
CopyOnWriteArrayListAlternative thread-safe list without manual synchronization for iteration.

Key Takeaways

Use Collections.synchronizedList to wrap ArrayList for thread-safe access.
Always synchronize on the list object when iterating over a synchronized list.
Failing to synchronize during iteration can cause runtime exceptions.
Consider CopyOnWriteArrayList for simpler thread-safe iteration.
Synchronization adds overhead; use only when multiple threads access the list.