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
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.