The monitorenter/monitorexit mechanism is used by the
Java synchronized statement to coordinate access to an object among
multiple threads. For example, when you write in Java code:
static void Sort(int [] array) {
// synchronize this operation so that some other thread can't
// manipulate the array while we are sorting it. This assumes that other
// threads also synchronize their accesses to the array.
synchronized(array) {
// now sort elements in array
}
}
then
JVM code like the following is generated:
.method static Sort([I)V
aload_0
monitorenter ; lock object in local variable 0
; now sort elements in array
aload_0
monitorexit ; finished with object in local variable 0
return
.end method
monitorenter
obtains an exclusive lock on the object referenced by objectref. There
are three possible scenarios:
If no other thread has locked the object, a new lock is established on the
object, and execution continues at the next instruction.
If the object is currently locked by another thread, monitorenter
blocks, waiting for the other thread to unlock the object.
If the current thread already owns a lock on the object, a counter is
incremented - the lock will only be released when the counter returns to zero
(see monitorexit).