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

Manual Synchronization During Iteration

Why iteration requires explicit synchronization blocks even with synchronized wrappers to avoid ConcurrentModificationException.

Manual Synchronization During Iteration

You'll learn why even synchronized wrappers require extra locking during iteration to prevent crashes.

When you create a synchronized collection using Collections.synchronizedList or similar methods, Java automatically locks each individual method call. However, iteration is not a single method call—it's a series of method calls (hasNext(), next()) happening one after another. Between these calls, another thread could modify the collection, causing a ConcurrentModificationException.

The Core Problem

Think of iteration like reading a book aloud to an audience. Each word you read is protected (synchronized), but between words, someone might rip out pages. When you try to continue, you discover the book has changed—chaos ensues!

A synchronized collection only locks during each method call, not between calls. While you're iterating, another thread can sneak in and modify the collection after one next() completes but before the next hasNext() check.

The Solution

You must manually synchronize on the collection itself during the entire iteration block:

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

// WRONG - not thread-safe during iteration
for (String item : syncList) {  // ConcurrentModificationException risk!
    System.out.println(item);
}

// CORRECT - manually synchronized
synchronized (syncList) {
    for (String item : syncList) {
        System.out.println(item);
    }
}

By wrapping the entire iteration in a synchronized block on the collection object, you hold the lock continuously, preventing any other thread from modifying the collection until you're done iterating.

Key Takeaway: Synchronized wrappers protect individual operations but not multi-step operations like iteration—you must use explicit synchronized blocks around iteration to prevent ConcurrentModificationException.