简体   繁体   中英

Hashmap and hashtable in multithreaded environment

I am really confused on how these 2 collections behave in multithreaded environment.

Hash table is synchronized that means no 2 threads will be updating its value simultaneously right?

Look at ConcurrentHashMap s 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM