Monday, April 3, 2017

Difference between Lock and Monitor - Java Concurrency

A lock is like a privilege that only one thread can "possess" at any one time.

If a thread wants to lock a particular object or class, it asks the JVM. 
When the thread no longer needs the lock, it returns it to the JVM. If another thread has requested the same lock, the JVM passes the lock to that thread.


The JVM uses locks in conjunction with monitors. A monitor is basically a guardian in that it watches over a sequence of code, making sure only one thread at a time executes the code.

Each monitor is associated with an object reference. When a thread arrives at the first instruction in a block of code that is under the watchful eye of a monitor, the thread must obtain a lock on the referenced object.
In Java language terminology, the coordination of multiple threads that must access shared data is called synchronization.


Two opcodes, MonitorEnter and MonitorExit, are used for synchronization blocks within methods.


When MonitorEnter is encountered by the Java virtual machine, it acquires the lock for the object referred to by objectref on the stack. If the thread already owns the lock for that object, a count is incremented. Each time MonitorExit is executed for the thread on the object, the count is decremented. When the count reaches zero, the monitor is released.

No comments: