Enter monitor for object
Bytecode
Type | Description |
u1 | monitorenter opcode = 0xC2 (194) |
Description
The objectref must be of type reference
.
Each object has a monitor associated with it. The thread that executes monitorenter gains ownership of the monitor associated with objectref. If another thread already owns the monitor associated with objectref, the current thread waits until the object is unlocked, then tries again to gain ownership. If the current thread already owns the monitor associated with objectref, it increments a counter in the monitor indicating the number of times this thread has entered the monitor. If the monitor associated with objectref is not owned by any thread, the current thread becomes the owner of the monitor, setting the entry count of this monitor to 1.
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:
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
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).
Exceptioms
NullPointerException - the object reference on the stack is null.
Notes
1. Methods which are marked as synchronized implicitly perform a monitorenter when invoked, and a monitorexit when they return.
2. Java's wait(), notify() and notifyAll() methods also interact with locks on objects.