my dog learned polymorphism
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Collection question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Collection question" Watch "Collection question" New topic

Collection question

Maulin Vasavada
Ranch Hand

Joined: Nov 04, 2001
Posts: 1873
Hi all,
'm glad to be back again after a while. i have a question about Collections class.
it says on Sun api that,
It is imperative that the user manually synchronize on the returned collection when iterating over it:
Collection c = Collections.synchronizedCollection(myCollection);
synchronized(c) {
Iterator i = c.iterator(); // Must be in the synchronized block
while (i.hasNext())

Failure to follow this advice may result in non-deterministic behavior.
I didnt follow this. If we have "c" object synchronized then why we need to do it again for iterator method even if it's using multiple calls into the collection?
can anybody expalin this to me?
Jim Hall
Ranch Hand

Joined: Nov 29, 2001
Posts: 162
From API:
The iterators returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
Maulin Vasavada
Ranch Hand

Joined: Nov 04, 2001
Posts: 1873
thanks jim. i didnt thought of that.
I agree. Here's the link:
subject: Collection question
It's not a secret anymore!