Codectionary / Developer documentation / Java

Explicit Locking with ReentrantLock

ReentrantLock provides explicit mutual exclusion with optional timed or interruptible acquisition. The same thread may acquire it repeatedly, but must unlock the same number of times. Save as Main.java and run with a Java 17+ JDK: java Main.java.

Syntax

lock.lock(); try { criticalSection(); } finally { lock.unlock(); }

Examples

Explicit Locking with ReentrantLock

Save as Main.java and run with a Java 17+ JDK: java Main.java.

import java.util.concurrent.locks.ReentrantLock;

public class Main {
  public static void main(String[] args) throws Exception {
    ReentrantLock lock = new ReentrantLock();
    lock.lock();
    try {
      System.out.println(lock.isHeldByCurrentThread());
      lock.lock();
      try { System.out.println(lock.getHoldCount()); }
      finally { lock.unlock(); }
    } finally { lock.unlock(); }
    System.out.println(lock.isLocked());
  }
}
  1. Expected output: true 2 false
  2. The nested acquisition succeeds because ownership is reentrant. Both finally blocks run, returning the hold count to zero.

Best practices

  • Place unlock in finally immediately after successful acquisition.
  • Prefer synchronized when its simpler scope provides all the behavior needed.

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading