In: Computer Science
Explain what the JVM does when it encounters a synchronized directive. Hint: consider carefully what is synchronized.
Answer:
In Java, sharing of resources / data among the multiple thread is managed via the synchronized keyword. Synchronization in Java guarantees that no two threads can execute a synchronized method which requires the same lock simultaneously or concurrently. If sharing of data among multiple threads is not properly manged, then the program will have unpredictable behavior.
Whenever JVM encounters synchronized directive or method, or can say that when a thread enters into java synchronized method or blocks it acquires a lock and releases the lock whenever it leaves java synchronized method or block. The lock is released even if thread leaves synchronized method after completion or due to any Error or Exception.
For an instance method, the JVM acquires the lock associated with the object upon which the method is being invoked. For a class method, it acquires the lock associated with the class to which the method belongs.
Please give thumbsup, if you like it. Thanks.