javalockingdeadlockreentrancy

Reentrant lock and deadlock with Java


Can someone explain to me how Reentrant lock and deadlock relate to each other with Java code (pseudo) example?


Solution

  • A reentrant locking mechanism allows the thread holding the lock to re-enter a critical section. This means that you can do something like this:

    public synchronized void functionOne() {
    
        // do something
    
        functionTwo();
    
        // do something else
    
        // redundant, but permitted...
        synchronized(this) {
            // do more stuff
        }    
    }
    
    public synchronized void functionTwo() {
         // do even more stuff!
    }
    

    In a non-reentrant lock, you would have a deadlock situation when you try to call functionTwo() from functionOne() because the thread would have to wait for the lock...which it holds itself.

    Deadlock, of course, is the evil situation in which Thread 1 holds lock A and is waiting for lock B while Thread 2 holds lock B and is waiting for lock A. Thus, neither can continue. This code sample creates a deadlock:

    public synchronized void deadlock() throws InterruptedException {
        Thread th = new Thread() {
            public void run() {
                deadlock();
            }
        }.start();
    
        th.join();
    }
    

    The calling thread tries to wait around for the spawned thread, which in turn can't call deadlock() until the caller has exited. Ka-boom!