If a java synchronized method calls another synchronized method, does the object still has the lock of the original synchronized method?
-
3Yes. And when thread will try to invoke another method synchronized on same lock it will not wait, but acquire it again (it will increase counter of how many times it acquired that lock). Then when it will end that additional method it will return that lock (by reducing that counter). To read more about it research "re-entrant lock". You will find questions like [What is the Re-entrant lock and concept in general?](https://stackoverflow.com/q/1312259) – Pshemo Jul 01 '20 at 21:24
-
2Are you also asking about what happens when these are two different locks? – akuzminykh Jul 02 '20 at 00:22
1 Answers
For better understanding about Synchronization and Locks must know the following :
I. Object Lock
II. Class Lock
The below explanation only for base or low level understanding about Object Lock
Related to your question:
NOTE:
Only Threads can Acquire or Release Locks.
Each Object has it's Own Object Lock. (Specific to Object / Instance)
Class Lock will be only One. (Specific to Class)
Example:
Employee e1 = new Employee();
Employee e2 = new Employee();
Employee e3 = new Employee();
Total Available Object Lock Count : 3 (THREE)
Total Available Class Lock Count : 1 (ONE)
synchronized method calls another synchronized method - On Same Object:
Once Thread acquired Lock of that object then only it will allow to access
synchronized methods / blocks. Once the Lock acquired then that thread can able to call or access any other synchronized methods in that object with Same Lock.Note: In this case Thread has only One Lock.
synchronized method calls another synchronized method - On Another Object:
Once Thread acquired current Object Lock then thread calls another method on some other object then need to acquire Lock of Another Object then Thread has Two Object Locks.
Note: In this case Thread has Two Locks.
synchronized method calls another synchronized method - On Multiple Objects:
Method Chaining processing thread passing through multiple synchronized methods then it will acquire corresponding Object Locks, Once its finish execution of method it will release the lock of that corresponding Object.
Note: In this case Thread Acquired Multiple Object Locks.
Note: One Thread can Acquire Multiple Locks (or) 'N' - Number of Locks.

- 1
- 3