Nested Locks

Let’s examine our BusyFlag class yet again. Suppose we add another method that finds out which thread owns the lock. This getBusyFlagOwner() method simply returns the busyflag, which just so happens to be the thread object that owns the lock. An implementation is as follows:

public synchronized Thread getBusyFlagOwner() {
            
    return busyflag;
}

Furthermore, let’s make a modification to the freeBusyFlag() method to use this new getBusyFlagOwner() method:

public synchronized void freeBusyFlag () {
    if (getBusyFlagOwner() == Thread.currentThread()) {
        busyflag = null;
    }
}

In this version of the freeBusyFlag() method, we make a call to the getBusyFlagOwner() method to see if the current thread is the owner before freeing the busyflag. What is interesting here is that both the freeBusyFlag() and the getBusyFlagOwner() methods are synchronized. So what happens? Does the thread hang at the getBusyFlagOwner() method while waiting for the freeBusyFlag() method to free the object lock? If not, and the getBusyFlagOwner() method is allowed to run, what happens when that method completes? Does it free the object lock even though the freeBusyFlag() method still needs it? The answer to all these questions is that it all works the way you want it to.

Get Java Threads, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.