Today's Question:  What weekend projects have you created?        GIVE A SHOUT

Technical Article => Programming =>  Java

Java SynchronizedList and Iterator

  winboy      2015-12-03 03:04:08      1,610    0

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


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(;

    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.



Share on Facebook  Share on Twitter  Share on Google+  Share on Weibo  Share on Reddit  Share on Digg  Share on Tumblr    Delicious


No related articles


No comment for this article.


You want to mislead me? No way!

By sonic0002