Hashmap and hashtable in multithreaded environment

て烟熏妆下的殇ゞ 提交于 2019-11-29 13:56:20

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 Goetz http://jcip.net/

I still learn something new every time I read it.

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 :-)

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.

Yes, all the methods are done atomically, but values() method not (see docs).

Paul was faster than me recommending you the java.util.concurrent package, which gives you a very fine control and data structures for multithreade environments.

Hashtables are synchronized but they're an old implementation that you could almost say is deprecated. Also, they don't allow null keys (maybe not null values either? not sure).

One problem is that although every method call is synchronized, most interesting actions require more than one call so you have to synchronize around the several calls.

A similar level of synchronization can be obtained for HashMaps by calling:

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

which wraps a map in synchronized method calls. But this has the same concurrency drawbacks as Hashtable.

As Paul says, ConcurrentHashMaps provide thread safe maps with additional useful methods for atomic updates.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!