| Author |
Lock Reentrance
|
meeta gaur
Ranch Hand
Joined: Dec 05, 2012
Posts: 225
|
|
Lock Reentrance
Synchronized blocks in Java are reentrant. This means, that if a Java thread enters a synchronized block of code, and thereby take the lock on the monitor object the block is synchronized on, the thread can enter other Java code blocks synchronized on the same monitor object. Here is an example:
Notice how both outer() and inner() are declared synchronized, which in Java is equivalent to a synchronized(this) block. If a thread calls outer() there is no problem calling inner() from inside outer(), since both methods (or blocks) are synchronized on the same monitor object ("this"). If a thread already holds the lock on a monitor object, it has access to all blocks synchronized on the same monitor object. This is called reentrance. The thread can reenter any block of code for which it already holds the lock.
The lock implementation shown earlier is not reentrant. If we rewrite the Reentrant class like below, the thread calling outer() will be blocked inside the lock.lock() in the inner() method.
A thread calling outer() will first lock the Lock instance. Then it will call inner(). Inside the inner() method the thread will again try to lock the Lock instance. This will fail (meaning the thread will be blocked), since the Lock instance was locked already in the outer() method.
The reason the thread will be blocked the second time it calls lock() without having called unlock() in between, is apparent when we look at the lock()
I don't understand why did he say there is no reentrant in first example ?
When any thread calls synchronized outer method then it will lock monitor object, then inside outer there is again call inner method which is also synchronized on same monitor object, so how it is not re-entrant ?
|
OCAJP
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16695
|
|
meeta gaur wrote:
I don't understand why did he say there is no reentrant in first example ?
When any thread calls synchronized outer method then it will lock monitor object, then inside outer there is again call inner method which is also synchronized on same monitor object, so how it is not re-entrant ?
Perhaps you took the book out of context? Maybe the book was referring to a previous lock *implementation*, and not the example you are referring to.
Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
 |
|
|
subject: Lock Reentrance
|
|
|