Java SynchronizedList and Iterator

Summary

When using Collections.synchronizedList to create a thread-safe list, it's imperative to manually synchronize on the list object itself during iteration. This explicit synchronization is crucial because Iterators are not inherently thread-safe and do not prevent concurrent modifications, which can lead to ConcurrentModificationException or unpredictable behavior. The design of Iterator assumes no structural changes to the underlying collection while it is being traversed. Therefore, developers must ensure the iteration block is synchronized to maintain thread safety, even with a synchronized wrapper.

While reading some material about concurrency, I come up with some writing about using SynchronizedList wrap about normal List to enable synchronization.

 

But one interesting thing is

http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#synchronizedList%28java.util.List%29

 

It says

    It is imperative that the user manually synchronize on the returned list when iterating over it:

    1   List list = Collections.synchronizedList(new ArrayList());

    2       ...

    3   synchronized (list) {

    4       Iterator i = list.iterator(); // Must be in synchronized block

    5       while (i.hasNext())

    6           foo(i.next());

    7   } 

 

Even after making a SynchronizedList, if you want to use its iterator, you still need to make the list synchronized before you use the iterator.

 

That's because the nature of Iterator.

 

I always has this question: Why is Iterator useful?

For any Java collection, I can call it's own traversal method and maintain index to trace, use while/for loop to do, etc.

But there is case that another method out of the scope of current environment need to access an object in this environment, and that method doesn't care what object it is. It just want to Iterate the object.

In this case, Iterator gave a kind of interface to those kind of objects, List, Set, Vector, etc.

 

After talking about benefit and usage of Iterator, then when using Iterator, you always need to synchronize Iterator, or it will fail with ConcurrentModificationException, or result in unpredictive behavior, depends on whether the object itself is fail-fast or not.

It makes sense, cause Iterator's nature is you should not modify the object while using its Iterator.

 

  RELATED

No related programming articles found. Browse all programming tutorials and articles.

  COMMENTS

0

No comment for this article.