void method1() {
synchronized(this) { // Acquires intrinsic lock
method2();
}
}
void method2() {
synchronized(this) {} // Acquires same lock due to Reentrant synchronization
}
First time lock is acquired in method1 which calls synchronized method2 where second time it gets the same lock .
Now my doubt is when synchronized block ends in method2() does unlocking happens here first time and returns to synchronized block of method1() where again unlocking happens second time .
Does it internally manages count of locks like in ReentrantLock ?
Does it internally manages count of locks like in ReentrantLock ?
Yes. From JLS section 17.1 - emphasis mine.
The Java programming language provides multiple mechanisms for communicating between threads. The most basic of these methods is synchronization, which is implemented using monitors. Each object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor. Any other threads attempting to lock that monitor are blocked until they can obtain a lock on that monitor. A thread
t
may lock a particular monitor multiple times; each unlock reverses the effect of one lock operation.
See more on this question at Stackoverflow