• Post Reply Bookmark Topic Watch Topic
  • New Topic

Iterating over Synchronized Map

 
John Wright
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the method that contains the iteration code over a synchronized HashMap (i.e. one optained from Collection.synchonizedMap(new HashMap()) is synchronized must I still synchronize on the underlying Map. Or must synchronization on the underlying Map only take place if two threads are iterating at the same time not if one thread is iterating and one or more other threads are reading and writing the Map. The following documenation from Sun confuses me a little bit:
"In the face of concurrent access, it is imperative that the user manually synchronize on the returned collection when iterating over it. This is because iteration is accomplished via multiple calls into the collection, which must be composed into a single atomic operation. The idiom to iterate over a
wrapper-synchronized collection is:
Collection c = Collections.synchronizedCollection(myCollection);
synchronized(c) {
Iterator i = c.iterator(); // Must be in synchronized block!
while (i.hasNext())
foo(i.next());
}
Failure to follow this advice may result in non-deterministic behavior. "
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by John Wright:
If the method that contains the iteration code over a synchronized HashMap (i.e. one optained from Collection.synchonizedMap(new HashMap()) is synchronized must I still synchronize on the underlying Map.

Yes. Other threads reading the map are not a problem, but if the map is being modified then bad things happen. The iterator for a synchronized collection is not synchronized itself. Access through the iterator is equivalent to access through the underlying unsynchronized collection.
Iterators don't like it anyway if the collection is modified in any way except through the iterator itself.
- Peter
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!