Today's Question:  What does your personal desk look like?        GIVE A SHOUT

Java SynchronizedList and Iterator

  winboy        2015-12-03 03:04:08       8,294        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

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.

 

 

Share on Facebook  Share on Twitter  Share on Weibo  Share on Reddit 

  RELATED


No related articles

  0 COMMENT


No comment for this article.