Junior — Middle
Can a single-threaded call to a method declared with synchronized re-enter the same method during its execution?
sobes.tech AI
Answer from AI
Yes, a single-threaded call to a method declared with the synchronized keyword can re-enter the same method during its execution. This is called a recursive lock (reentrant lock).
In Java, the monitor (lock) associated with a synchronized block or method maintains a hold count. If a thread already owns the monitor, it can re-enter the synchronized block without blocking, increasing the count. The monitor will only be released when the thread exits all nested synchronized blocks, and the count reaches zero.
Example:
public class ReentrantExample {
public synchronized void method() {
System.out.println("Entering method");
// Recursive call
if (condition) {
method();
}
System.out.println("Exiting method");
}
}
In this example, the thread can safely re-enter the method without blocking.