aspose file tools
The moose likes Threads and Synchronization and the fly likes hashmap and synchronization 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 » Java » Threads and Synchronization
Reply Bookmark "hashmap and synchronization" Watch "hashmap and synchronization" New topic
Author

hashmap and synchronization

Vidar x Langberget
Greenhorn

Joined: May 12, 2003
Posts: 10
Hi!
I'm developing a web application, which stores a relatively low number of objects in a hashmap.
The plan is to check the database for updates every 10 minutes or so, and if there has been any changes to the database, the hashmap must be updated to reflect this.
I'm not sure how to handle synchronization issues. Is it sufficient to synchronize on just the update method? Or should I use Collections.synchronizedMap()?
Vidar
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18670
That's a bit hard to say. According to the API for HashMap, you must synchronize all access in this case - at least if any puts or removes will be performed. In practice you may be able to get away with not synchronizing the get() methods - but you're relying on implementation-specific details if you do. Test carefully, and be aware that upgrading to a new JVM may change behavior drastically. Some other issues:
If you're using any Iterators associated with the map and a put() or remove() is performed by the (synchronized) update, the (unsunchronized) Iterator will fail.
If the update performs any remove(), other threads attempting get() may throw NullPointerException.
Updates may not be immediately visible to unsynchronized thread - they may see an old copy of the data.
Generally I'd recommend when in doubt, synchronize. However there may be some applications where you find that the performance gain of removing synchronization is worth the other potential difficulties.


"I'm not back." - Bill Harding, Twister
 
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: hashmap and synchronization
 
Similar Threads
Hashmap
Hibernate 2: locking a row
Thread
synchronization
Locks