• Post Reply Bookmark Topic Watch Topic
  • New Topic

Synchronzing a HashMap on the same HashMap object

 
Arvind Sampath
Ranch Hand
Posts: 144
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is what the docs say about HashMaps reg synchronization

If multiple threads access this map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map.





Can I sychronize the block of code which operates on my HashMap, on the HashMap object itself?

Since the Iterator will throw an Exception if the underlying Map is modified externally during the course of the iteration, I have synchronzied the iteration code as well on the HashMap object.

Is it better to synchronize the iteration code or to create a new map using the existing map and iterated that map in a non synchronized block?


Cheers,
Arvind
 
Henry Wong
author
Sheriff
Posts: 22519
109
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can I sychronize the block of code which operates on my HashMap, on the HashMap object itself?

Since the Iterator will throw an Exception if the underlying Map is modified externally during the course of the iteration, I have synchronzied the iteration code as well on the HashMap object.

Is it better to synchronize the iteration code or to create a new map using the existing map and iterated that map in a non synchronized block?


Without getting into a debate about whether this is a good idea or not... externally synchronizing on the hashmap is a very common technique. It should work fine.

For your second question -- It depends. If the collection size is small, and the iteration operation is fast, then it is most likely okay. Also if iteration is uncommon, then it is also likely okay.

In any case, another option to cloning (if you are using Java 5), is to use the copy-on-write collections. These collections will only clone the collection if a write operation occurs while iterating.

Henry
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!