What will happen if in a ConcurrentHashMap all the objects have same hashcode? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What will happen if in a ConcurrentHashMap all the objects have same hashcode?

I was reading about the ConcurrentHashMap, that it uses Bucket level locking i.e. each bucket has a separate lock. My question is what will happen if there are 10000 entries in a ConcurrentHashMap, and they all have the same hashcode and end up in a same bucket? I know this is an inefficiency of hashcode , but what if this happens, will each thread then have to wait for the other thread to release the lock on that bucket leading to poor performance?

14th May 2021, 6:54 PM
Satyam Joshi
Satyam Joshi - avatar
3 Answers
+ 3
From: https://www.baeldung.com/java-concurrent-map "hashCode matters: note that using many keys with exactly the same hashCode() is a sure way to slow down a performance of any hash table. To ameliorate impact when keys are Comparable, ConcurrentHashMap may use comparison order among keys to help break ties. Still, we should avoid using the same hashCode() as much as we can" So I think you are right.
14th May 2021, 7:09 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
Thanks Denise Roßberg , one more thing, "To ameliorate impact when keys are Comparable, ConcurrentHashMap may use comparison order among keys to help break ties."  "ConcurrentHashMap may use comparison order among keys" for what? To create buckets?
15th May 2021, 2:19 AM
Satyam Joshi
Satyam Joshi - avatar
+ 1
Unfortunately I don't know it. Maybe you need to look into the source code to find an answer.
15th May 2021, 9:01 AM
Denise Roßberg
Denise Roßberg - avatar