Monday, November 26, 2007

What would happen if locks in Java were non re-entrant

Locks in java are re-entrant , that aids locking to work effectively with Object Oriented Programming . Why ??

Just consider , if you have a base class

class Mybase{
public synchronized doStuff(){
}

}

Now If you have a child class extending the base class then,

public class MyChild extends MyBase{
public synchronized doStuff(){
super.doStuff();
}

}

This would cause a deadlock . Why ??

When on the child doStuff is called a lock on the MyBase object is obtained . Now in MyChild::doStuff when super.doStuff() is called the code would again try to get a new lock on
Mybase and if locks were non re-entrant then the thread would block and hence would cause a deadlock.