user3444882 user3444882 - 1 month ago 7
Java Question

Thread safe but does not prevent deadlock?

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?

Answer

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!