1
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 ?

Javed Solkar
  • 162
  • 11

2 Answers2

3

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

Yes internally jdk keeps track of reentrance.

As per oracle docs:

Recall that a thread cannot acquire a lock owned by another thread. But a thread can acquire a lock that it already owns. Allowing a thread to acquire the same lock more than once enables reentrant synchronization. This describes a situation where synchronized code, directly or indirectly, invokes a method that also contains synchronized code, and both sets of code use the same lock. Without reentrant synchronization, synchronized code would have to take many additional precautions to avoid having a thread cause itself to block.

See this for details.

SMA
  • 36,381
  • 8
  • 49
  • 73
  • Can you explain a little more on the last line of that quoted text? What does it mean to "cause itself a block"? How can a thread block itself? – Prashant Prakash Mar 18 '21 at 13:02