Intrinsic locks are re-entrant , means same thread can acquire the lock again.
How Reentrancy is implemented ?
Each lock has associated acquisition count and an owning thread.
When lock is unheld, count sets to 0
When thread acquires a lock, JVM sets the owner and sets count to 1.
If the same thread acquires the lock again, the count is incremented and when the owning thread exits the synchronized block, the count is decremented.
When the count reaches 0, the lock is released.
Why Reentrancy is required ?
Example
public class A {
public synchronized void disp() {
...
}
}
public class B extends A {
public synchronized void disp() {
System.out.println(toString() + ": calling disp");
super.disp();
}
}
public synchronized void disp() {
...
}
}
public class B extends A {
public synchronized void disp() {
System.out.println(toString() + ": calling disp");
super.disp();
}
}
Both methods in A and B classes are synchronized, each tries to acquire the lock on A.
If the intrinsic locks were not reentrant, the call to super.disp would never be able to acquire the lock because it would be considered already held.
No comments:
Post a Comment
Note: only a member of this blog may post a comment.