This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Collection question Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Collection question" Watch "Collection question" New topic
Author

Collection question

Maulin Vasavada
Ranch Hand

Joined: Nov 04, 2001
Posts: 1865
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())
foo(i.next());
}

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?
regards
maulin.


1. Have fun @ http://faq.javaranch.com/java/JavaRaq
2. Looking for simple infix2postfix conversion and postfix evaluation package? Click here
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.
HIH
Maulin Vasavada
Ranch Hand

Joined: Nov 04, 2001
Posts: 1865
hey,
thanks jim. i didnt thought of that.
regards
maulin.
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Collection question
 
Similar Threads
about java.util.Collections
Synchronized Collection Decorators
Synchronizing a Collection
please help, about synchronized block
Iterating over Synchronized Map