SoFunction
Updated on 2025-04-18

Interpretation of the release mechanism of synchronized lock

Release mechanism of synchronized lock

The release mechanism of synchronized lock is through the JVMMonitor lock modelandCounter mechanismAchieved.

The following are the specific release logic and trigger conditions:

1. The trigger conditions for lock release

The normal execution ends

When the thread is executedsynchronizedWhen a modified code block or method is called automatically by the JVMmonitorexitCommand release lock.

  • Synchronize code blocks:passmonitorenterandmonitorexitThe instruction explicitly controls the acquisition and release of the lock.
  • Synchronization method:passACC_SYNCHRONIZEDThe flag implicitly triggers the acquisition and release of the lock, and automatically releases the lock at the end of the method.

quit unexpectedly

  • IfsynchronizedUncaught exceptions are thrown in code blocks or methods, and the JVM will execute themmonitorexitCommand release lock.
  • Two are generated for synchronous code blocks during compilationmonitorexitDirective: One is used for normal exit and the other is used for exception path.

Explicit callwait()

  • The thread is insynchronizedCalling within the code blockwait()When
  • The lock will be temporarily released and the waiting state will be entered until other threads call itnotify()/notifyAll()Wake it up

2. The core mechanism of lock release

Counter decrement

  • Each object is associated with a Monitor lock and an internal counter is maintained (_count)。
  • Every time the thread enterssynchronizedThe counter is increased by 1 when the code blocks, and decrement is decreased by 1 when exiting.
  • When the counter is zeroed, the lock is completely released and other threads can compete to acquire.

State management of Monitor objects

  • The thread holding the lock (_owner: After releasing the lock,_ownerSet asnull, the counter is reset to zero.
  • Waiting for queue (_EntryListand_WaitSet: After the lock is released, the JVM will_EntryListor_WaitSetThe wakeup thread recompets for locks.

3. Examples of lock release in different scenarios

1. Synchronize code blocks

public void method() {
    synchronized (this) {
        // Code logic    } // Automatically execute monitoringexit release lock}

Whether it ends normally or throws an exception,monitorexitThe lock release will be triggered.

2. Synchronization method

public synchronized void method() {
    // Code logic} // Automatically release lock after the method

passACC_SYNCHRONIZEDFlags implicitly manage locks without explicit bytecode instructions.

3. Exceptional scenes

public void method() {
    synchronized (this) {
        throw new RuntimeException(); // Trigger an exception and automatically release the lock    }
}

The JVM executes even if the exception is not caughtmonitorexitCommand release lock.

4. The underlying implementation of lock release (bytecode level)

Synchronize code blocks

Generate after compilationmonitorenterand twomonitorexit(normal exit and exception exit) instruction:

public void method();
  Code:
     0: aload_0
     1: dup
     2: astore_1
     3: monitorenter     // Get the lock     4: ...              // Business code    13: monitorexit      // Exit the release lock normally    14: goto 20
    17: aload_1
    18: monitorexit      //Exception to release the lock    19: athrow
    20: return

Synchronization method

Method access flags includeACC_SYNCHRONIZED, JVM implicitly manages locks in method entry and exit.

5. Things to note

Operation that will not release the lock

  • ()()The lock will not be released.
  • Thread hangs (such assuspend()) will not release the lock either.

Reentrability

  • The same thread can acquire locks multiple times (counter increments)
  • The corresponding number of exit operations is required to be fully released

Summarize

The release of synchronized locks depends on the JVM's Monitor model and counter mechanism, and is triggered in the following ways:

  1. The code block or method ends normally.
  2. Uncaught exception thrown.
  3. Explicit callwait()
  4. Its bottom layer passesmonitorexitInstructions or implicit flags ensure correct release of locks and ensure thread safety.

The above is personal experience. I hope you can give you a reference and I hope you can support me more.