hashmap synchronization on get and put
1 posts in topic
Flat View  Flat View

Posted By:   Anonymous
Posted On:   Tuesday, August 7, 2001 04:36 PM

If I had two thread, one getting a value from a hashmap and the other concurrently putting a value into the hashmpa, do I need to synchronize the hashmap before each operation?


Re: hashmap synchronization on get and put

Posted By:   AlessandroA_Garbagnati  
Posted On:   Wednesday, August 8, 2001 10:23 AM


The short answer: yes, the best answer is incluided in the java.util.HashMap javadoc:

Note that this implementation is not synchronized. 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. If no such object exists, the map should be "wrapped" using the Collections.synchronizedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map:

Map m = Collections.synchronizedMap(new HashMap(...));

About | Sitemap | Contact