O'Reilly logo

Java Threads, Second Edition by Henry Wong, Scott Oaks

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required