Make delicious recipes!

Re-entrant Lock

In the Lock implementation shown above, imagine what would happen if a thread obtained the lock on some object and then called another function which also tried to obtain loc, basically something like this:


class ABC {

    Lock lck = new Lock ();

    public void parent () {
        lck.lock ();
        child ();
        lck.unlock ();
    }


    public void child () {
        lck.lock ();
        // do something
        lck.unlock ();
    }

}


Here, thread would obtain the lock in parent () and then call child () without releasing the lock. Since child () also tries to obtain the lock on the same object (this), the thread would wait forever. Basically the thread would continue to wait for other threads to release the lock which it is holding itself.

This situation means that the above lock implemented does not allow thread to re-enter, hence its not a reentrant lock.


Synchronized blocks in Java are reentrant. This means, that if a Java thread enters a synchronized block of code and thereby takes the lock on the monitor object the block is synchronized on, the same thread can enter other Java code blocks synchronized on the same monitor object.


A synchronized lock can be implemented as follows:





Like us on Facebook to remain in touch
with the latest in technology and tutorials!


Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Name:
Email: (Your email is not shared with anybody)
Comment:

Facebook comments:

Site Owner: Sachin Goyal