---
spec: JVMS
title: "The Java Virtual Machine Specification"
edition: "Java SE 25 Edition"
java_version: 25
chapter: "Chapter 3. Compiling for the Java Virtual Machine"
section: "3.14"
heading: "3.14. Synchronization"
parent: "Chapter 3. Compiling for the Java Virtual Machine"
source: https://docs.oracle.com/javase/specs/jvms/se25/html/jvms-3.html#jvms-3.14
id: "3.14"
url: https://jvm.obfuscated.software/jvms/se25/3.14.html
raw: https://jvm.obfuscated.software/jvms/se25/3.14.md
---

# 3.14. Synchronization

Synchronization in the Java Virtual Machine is implemented by monitor entry and exit, either explicitly (by use of the *monitorenter* and *monitorexit* instructions) or implicitly (by the method invocation and return instructions).

For code written in the Java programming language, perhaps the most common form of synchronization is the `synchronized` method. A `synchronized` method is not normally implemented using *monitorenter* and *monitorexit*. Rather, it is simply distinguished in the run-time constant pool by the `ACC_SYNCHRONIZED` flag, which is checked by the method invocation instructions ([§2.11.10](2.11.10.md)).

The *monitorenter* and *monitorexit* instructions enable the compilation of `synchronized` statements. For example:

```
void onlyMe(Foo f) {
    synchronized(f) {
        doSomething();
    }
}
```

is compiled to:

```
Method void onlyMe(Foo)
0   aload_1             // Push f
1   dup                 // Duplicate it on the stack
2   astore_2            // Store duplicate in local variable 2
3   monitorenter        // Enter the monitor associated with f
4   aload_0             // Holding the monitor, pass this and...
5   invokevirtual #5    // ...call Example.doSomething()V
8   aload_2             // Push local variable 2 (f)
9   monitorexit         // Exit the monitor associated with f
10  goto 18             // Complete the method normally
13  astore_3            // In case of any throw, end up here
14  aload_2             // Push local variable 2 (f)
15  monitorexit         // Be sure to exit the monitor!
16  aload_3             // Push thrown value...
17  athrow              // ...and rethrow value to the invoker
18  return              // Return in the normal case
Exception table:
From    To      Target      Type
4       10      13          any
13      16      13          any
```

The compiler ensures that at any method invocation completion, a *monitorexit* instruction will have been executed for each *monitorenter* instruction executed since the method invocation. This is the case whether the method invocation completes normally ([§2.6.4](2.6.4.md)) or abruptly ([§2.6.5](2.6.5.md)). To enforce proper pairing of *monitorenter* and *monitorexit* instructions on abrupt method invocation completion, the compiler generates exception handlers ([§2.10](2.10.md)) that will match any exception and whose associated code executes the necessary *monitorexit* instructions.
