Deadlock
While
it is not too difficult to check if a thread already owns a lock
before grabbing it, is it possible to prevent deadlock of any kind?
Before we try to answer this question, let’s look further into
just what deadlock is. Simplistically, deadlock is when two or more
threads are waiting for two or more locks to be freed and the
circumstances in the program are such that the locks will never be
freed. We saw this occur earlier, when we made the
getBusyFlag() method synchronized. The fact that
the freeBusyFlag() method was also synchronized
made it impossible for the busyflag to be freed
until the getBusyFlag() method returned. Since
the getBusyFlag() method was waiting for the
busyflag to be freed, it would wait forever.
That deadlock was caused by an object lock grabbed by the Java synchronization primitive and our own implementation of a lock mechanism, the BusyFlag class. Can this deadlock situation also be caused only with Java’s synchronization primitives? The answer to this question is yes; furthermore, it may be difficult to predict deadlock or to detect deadlock when it occurs. Code that runs correctly every time during testing may contain potential deadlocks that occur only under certain conditions or on certain implementations of the Java virtual machine. To better illustrate this problem, let’s examine some possible methods that may exist in any database system:
public void removeUseless(Folder file) { synchronized (file) { if (file.isUseless()) { Cabinet directory ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access