If a thread calls outer(), it can also call inner() from inside outer(), because both methods are synchronized on the same monitor object ("this")
public class Reentrant{
public synchronized outer(){
inner();
}
public synchronized inner(){
//do something
}
}
A customer lock can prevent reentrant. Now the thread calling outer() will be blocked at lock.lock() inside the inner() method.
public class Lock{
private boolean isLocked = false;
public synchronized void lock()
throws InterruptedException{
while(isLocked){
wait();
}
isLocked = true;
}
public synchronized void unlock(){
isLocked = false;
notify();
}
}
public class NotReentrant{
Lock lock = new Lock();
public outer(){
lock.lock();
inner();
lock.unlock();
}
public synchronized inner(){
lock.lock();
//do something
lock.unlock();
}
}
Reference: Locks in Java
No comments:
Post a Comment