Reentrant Monitors in Java: Understanding Thread Synchronization
Discover reentrant monitors in Java, which allow a thread to reuse the same monitor for different synchronized methods. Learn how this feature helps avoid deadlocks by enabling a thread to reacquire a lock it already holds, improving thread synchronization and efficiency.
Reentrant Monitor in Java
In Java, monitors are reentrant, which means a thread can reuse the same monitor for different synchronized methods if the methods are called from within each other.
Advantage of Reentrant Monitor
One major advantage of reentrant monitors is that they eliminate the possibility of a single thread deadlocking when trying to reacquire a lock it already holds.
Understanding Reentrant Monitor with Example
Let's illustrate the concept of reentrant monitors with the following example:
FileName: Reentrant.java
class Reentrant {
public synchronized void m() {
n();
System.out.println("This is m() method");
}
public synchronized void n() {
System.out.println("This is n() method");
}
}
In the Reentrant
class above, both m()
and n()
methods are synchronized. The m()
method internally calls the n()
method.
FileName: ReentrantExample.java
public class ReentrantExample {
public static void main(String args[]) {
final Reentrant r = new Reentrant();
Thread t1 = new Thread() {
public void run() {
r.m(); // calling method of Reentrant class
}
};
t1.start();
}
}
Output
This is n() method
This is m() method
Explanation
When t1.start()
is executed, it creates a new thread that calls the m()
method of the Reentrant
class. Inside m()
, it calls the n()
method. Both methods are synchronized, and since they are called from the same thread, the thread can reacquire the lock on the monitor it already holds.