Course contentsShow
← Java
Lesson 2674 of 2,87049. Synchronization and LockingFree lesson

Lock Acquisition Count: Entry and Exit Tracking

Understanding that the JVM maintains a count of how many times a thread has entered a lock and requires matching exits.

Lock Acquisition Count: Entry and Exit Tracking

What you'll learn: How the JVM internally tracks the number of times a thread enters and exits a reentrant lock to ensure proper release.

Because Java's intrinsic locks are reentrant, a single thread can acquire the same lock multiple times without deadlocking itself. But how does the JVM know when the lock is truly free? The answer lies in an internal counter.

How the Counter Works

When a thread acquires a lock for the first time, the JVM sets an internal acquisition count to 1. Each subsequent reentrant acquisition by the same thread increments this counter. Every time the thread exits a synchronized block or method on that lock, the counter decrements by 1.

The lock is only released—made available to other threads—when the count reaches zero.

Why This Matters

Think of it like entering and exiting nested rooms in a building. If you enter three rooms deep (acquisition count = 3), you must exit three times before you're truly outside. If you only exited twice, you'd still be inside, and the door would remain locked to others.

This mechanism ensures that:

  • Balanced entry/exit: Every lock acquisition must have a matching release
  • Safe reentrancy: The thread maintains exclusive access through nested calls
  • Eventual release: Only when all nested synchronized contexts complete does the lock become available

Example Pattern

synchronized void methodA() {  // count: 0 → 1
    // do work
    methodB();                 // still synchronized
}                              // count: 1 → 0 (lock released)

synchronized void methodB() {  // count: 1 → 2 (reentrant)
    // do work
}                              // count: 2 → 1 (not released yet)

When methodA calls methodB, the acquisition count goes from 1 to 2. Only after both methods complete does the count return to 0, releasing the lock.

Key Takeaway:
The JVM tracks lock acquisition depth with an internal counter, requiring each entry to have a matching exit before releasing the lock to other threads.