monitorenter 0xc2

Pops an object and locks its monitor (start of synchronized).

Opcode
0xc2 (194)
Family
Monitors
Operands
none
Length
1 byte
Operand stack
…, objectref → …
Can throw
NullPointerException

What it does

Locks the object's monitor, waiting if another thread holds it. A thread that already holds it just increments its count.

javac emits it only for synchronized blocks. A synchronized method has no monitorenter: the ACC_SYNCHRONIZED flag tells the JVM to lock on entry and unlock on exit.

How often javac uses it

In JDK 25.0.5's java.base module, monitorenter appears 959 times in 244 of its 7,391 classes: 0.05% of all instructions, the 112th most common of 194 opcodes in use. Some of the methods that use it: java.io.BufferedReader.read, java.io.BufferedWriter.flushBuffer, java.io.CharArrayReader.read, java.io.CharArrayWriter.write.

Examples

From the sample classes, compiled by javac 25 with -g. Each Java line is shown above the bytecode it compiled to; monitorenter is highlighted.

void increment() in Sync, compiled by javac 25
7synchronized (lock) {
0aload_0 // this
1getfield #7// Sync.lock : Object
4dup
8count++;
7aload_0 // this
8dup
9getfield #13// Sync.count : int
13iadd
14putfield #13// Sync.count : int
… 9 instructions after

Open in the viewer

void bump() in Switches, compiled by javac 25
54synchronized (lock) {
0aload_0 // this
1getfield #7// Switches.lock : Object
4dup
55count++;
7aload_0 // this
8dup
9getfield #63// Switches.count : int
13iadd
14putfield #63// Switches.count : int
… 9 instructions after

Open in the viewer

Related instructions

monitorexit Pops an object and unlocks its monitor.athrow Throws the exception on top of the stack.

Specification: JVMS §6.5, monitorenter (Java SE 25).