I came across this line which states that "However, even though all operations are thread-safe, retrieval operations do not entail locking, and there is not any support for locking the entire table in a way that prevents all access"in the overall description of Java class [ConcurrentHashMap] (https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html). My question is: does this mean that the ConcurrentHasMap does not prevent dead lock? Also I thought being thread-safe imply no dead lock will take place?
You get things the wrong way: whenever you create a design that requires locking, you open up the possibility for dead locks.
That doesn't necessarily mean that any such architecture is per se vulnerable to dead-locks.
Example: a typical dead lock situation is when thread A has lock L1 and waits for lock L2; whereas thread B holds L2 and needs L1. If you only have one lock object, then that scenario is one .. that can't happen.
In other words: you are not using class X it would prevent deadlocks. That is not possible. If at all, you might be using class X because it offers you functionality that allows you to come up with a "guaranteed-dead-lock-free" design!
A deadlock can occur only when there are two different locks, i.e. when you are holding a lock and waiting for another lock to release. (There are more conditions on deadlocks, however).
As the ConcurrentHashMap tries to avoid locks where possible, you are not able to acquire a lock with operations only on the map that the map may wait for. Hence, operations only on the map do not cause deadlocks.
However, thread-safety does not mean deadlock free. It only guarantees that the code will operate according to its interface, even when called from multiple threads. Making a class thread-safe usually includes adding locks to guarantee safe execution.
You may also want to have a look at the Wikipedia article.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With