Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 432
Pupusa Avatar asked Dec 25 '22 00:12

Pupusa


2 Answers

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!

like image 97
GhostCat Avatar answered Dec 28 '22 06:12

GhostCat


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.

like image 45
Martin Nyolt Avatar answered Dec 28 '22 07:12

Martin Nyolt