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());
}
}- Expected output: true 2 false
- 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