monitorenter

Operation

monitorenter
Enter monitor for object

Forms
monitorenter = 194 (0xc2)

Stack
..., objectref ...

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.

Runtime Exception
If objectref is null, monitorenter throws a NullPointerException.

Notes
For detailed information about threads and monitors in the Java Virtual Machine, see Chapter 8, "Threads and Locks."

The monitorenter instruction may be used with a monitorexit instruction to implement a Java synchronized block. The monitorenter instruction is not used in the implementation of synchronized methods, although it provides equivalent semantics; monitor entry on invocation of a synchronized method is handled implicitly by the Java Virtual Machine's method invocation instructions. See §7.14, in "Compiling for the Java Virtual Machine," for more information on the use of the monitorenter and monitorexit instructions.

The association of a monitor with an object may be managed in various ways that are beyond the scope of this specification. For instance, the monitor may be allocated and deallocated at the same time as the object. Alternatively, it may be dynamically allocated at the time when a thread attempts to gain exclusive access to the object and freed at some later time when no thread remains in the monitor for the object.

The synchronization constructs of the Java Language require support for operations on monitors besides entry and exit, including waiting on a monitor (Object.wait) and notifying other threads waiting in a monitor (Object.notify and Object.notifyAll). These operations are supported in the standard package java.lang, supplied with the Java Virtual Machine. No explicit support for these operations appears in the instruction set of the Java Virtual Machine.