"is a hashmap thread-safe for different keys?" Code Answer


in @dotsid's answer he says this:

if you change a hashmap in any way then your code is simply broken.

he is correct. a hashmap that is updated without synchronization will break even if the threads are using disjoint sets of keys. here are some of the things that can go wrong.

  • if one thread does a put, then another thread may see a stale value for the hashmap's size.

  • when a thread does a put that triggers a rebuild of the table, another thread may see transient or stale versions of the hashtable array reference, its size, its contents or the hash chains. chaos may ensue.

  • when a thread does a put for a key that collides with some key used by some other thread, and the latter thread does a put for its key, then the latter might see a stale copy of hash chain reference. chaos may ensue.

  • when one thread probes the table with a key that collides with one of some other thread's keys, it may encounter that key on the chain. it will call equals on that key, and if the threads are not synchronized, the equals method may encounter stale state in that key.

and if you have two threads simultaneously doing put or remove requests, there are numerous opportunities for race conditions.

i can think of three solutions:

  1. use a concurrenthashmap.
  2. use a regular hashmap but synchronize on the outside; e.g. using primitive mutexes, lock objects, etcetera.
  3. use a different hashmap for each thread. if the threads really have a disjoint set of keys, then there should be no need (from an algorithmic perspective) for them to share a single map. indeed, if your algorithms involve the threads iterating the keys, values or entries of the map at some point, splitting the single map into multiple maps could give a significant speedup for that part of the processing.
By Denis Tulskiy on July 21 2022

Answers related to “is a hashmap thread-safe for different keys?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.