Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Lock Reentrance

 
meeta gaur
Ranch Hand
Posts: 305
Notepad Tomcat Server Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ?
 
Henry Wong
author
Marshal
Pie
Posts: 20896
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic