Course contentsShow
← Java
Lesson 1248 of 2,87028. Collections Utility ClassFree lesson

Collections.synchronizedList and Its Guarantees

Using synchronizedList to wrap ArrayList or LinkedList for thread-safe access in concurrent environments.

Collections.synchronizedList and Its Guarantees

What You'll Learn

You'll learn how to wrap an ArrayList or LinkedList with Collections.synchronizedList() to make it safe for access by multiple threads simultaneously.

The Problem with Regular Lists in Concurrent Code

As you learned previously, regular collections like ArrayList and LinkedList aren't thread-safe. When multiple threads modify them at the same time, you can get corrupted data or crashes.

The synchronizedList Wrapper

Collections.synchronizedList() creates a thread-safe wrapper around any List. Think of it like putting your list inside a lockbox—only one thread can open the box and modify the list at a time.

List<String> unsafeList = new ArrayList<>();
List<String> safeList = Collections.synchronizedList(unsafeList);

// Now safeList can be safely accessed by multiple threads
safeList.add("Thread-safe item");

What Guarantees Does It Provide?

The wrapper synchronizes individual operations. When one thread calls add(), remove(), or get(), other threads must wait. This prevents corruption during single method calls.

Critical Limitation: Iteration Requires Manual Synchronization

Here's the catch: iteration is not automatically protected. You must manually synchronize:

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

Without this synchronized block, another thread could modify the list while you're iterating, causing a ConcurrentModificationException.

When to Use synchronizedList

Use it when:

  • Multiple threads need to share a single list
  • Concurrent modifications are occasional, not constant
  • You're willing to manually synchronize iterations and compound operations

Key Takeaway: Collections.synchronizedList() wraps a list to make individual method calls thread-safe, but you must still manually synchronize iteration and multi-step operations.