Hashmap and hashtable in multithreaded environment Hashmap and hashtable in multithreaded environment multithreading multithreading

Hashmap and hashtable in multithreaded environment


Look at ConcurrentHashMaps for Thread safe Maps.

They offer all the features of HashTable with a performance very close to a HashMap.

Performance is gained by instead of using a map wide lock, the collection maintains a list of 16 locks by default, each of which is used to lock a single bucket of the map. You can even configure the number of buckets :) Tweaking this can help performance depending on your data.

I can't recommend enough Java Concurrency in Practice by Brian Goetzhttp://jcip.net/

I still learn something new every time I read it.


Exactly, HashTable is synchronized that mean that it's safe to use it in multi-thread environment (many thread access the same HashTable) If two thread try to update the hashtable at the sametime, one of them will have to wait that the other thread finish his update.

HashMap is not synchronized, so it's faster, but you can have problem in a multi-thread environment.


Also note that Hashtable and Collections.synchronizedMap are safe only for individual operations. Any operations involving multiple keys or check-then-act that need to be atomic will not be so and additional client side locking will be required.

For example, you cannot write any of the following methods without additional locking:

  • swap the values at two different keys: swapValues(Map, Object k1, Object k2)

  • append the parameter to value at a key: appendToValue(Map, Object k1, String suffix)

And yes, all of this is covered in JCIP :-)