Performance Question
I have a singleton that is accessed by 10000+ clients.
The singleton has a Map that holds some objects. At initialization time the Map won't hold any objects. The Map will increase over time to about 1000 object.
Which solutions gives the best performance?
1. The Map is a Hashtable.
2. The Map is created as Collections.synchronizedMap(new HashMap());
3. The Map is a HashMap and use a read-write lock*. The read-write lock lets all readers get what they want right away when there is no write lock. If there is a write lock the readers have to wait until the lock is released.
*) Example at http://home.earthlink.net/~kohliaman/technical/rwlocks.html
[704 byte] By [
mafa] at [2007-9-26 1:17:37]

Hashtable and HashMap use the same algorithm based on Object.hashCode(). Here are the differences:
1) Hashtable is synchronized, HashMap is not and requiere the use of Collection.getSynchronizedMap( myHashMap )
2) HashTable do not accept null keys or null values, HashMap does.
if null key/values are not valid values in your program and you need a Thread-safe map, choose Hashtable, it will be faster than HashMap because:
1) it doesn't bother testing if keys/values are null or not
2) no wrapper to get the thread-safe behaviour => avoid one heap allocation each time you use a method.
and of course will reject null keys/values.
If you have to support null keys/values go for HashMap.
If your do not need thread safe stuff, go for HashMap too without the synchronized wrapper.
conclusion: Hashtable is faster than a synchronized(HashMap), the use of HashMap rather than HashTable is not a performance choice but rather a "how_it_will_be_used" choice (nul keys/values? thread safe?).
remu at 2007-6-29 0:47:23 >

> Hashtable and HashMap use the same algorithm based > 1) Hashtable is synchronized, HashMap is not and
> require the use of Collection.getSynchronizedMap(
> myHashMap )
There's no requirement to use
Collection.getSynchronizedMap()
This method is a helper method for people who want HashMap to act like Hashtable, which frankly isn't usually a good idea.
You are welcome to do the synchronizing yourself. This option will most probably outperform using a synchronized map as returned from the above method.
However, Using a plain HashMap with reader/writer locks will kick any of the other solutions perverbial butt, especially if the read/write ratio is high.
--dave