Meaningless Drivel is fun!*
The moose likes Threads and Synchronization and the fly likes Lock Reentrance Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Lock Reentrance" Watch "Lock Reentrance" New topic
Author

Lock Reentrance

meeta gaur
Ranch Hand

Joined: Dec 05, 2012
Posts: 305

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 ?


My one regret in life is that I am not someone else.
- Woody Allen
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18712
    
  40

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)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Lock Reentrance