Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

ReentrantLock — explicit reentrant mutual exclusion

ReentrantLock provides mutual exclusion while allowing its owner to acquire the same lock repeatedly. It requires explicit release and also offers tryLock() and associated Condition objects.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

ReentrantLock lock = new ReentrantLock();
lock.lock();
try {
    // critical section
} finally {
    lock.unlock();
}

ReentrantLock protects a critical section against simultaneous access by multiple threads. All accesses to the protected state must use the same lock. Unlike synchronized, release is explicit: immediately follow acquisition with try, and call unlock() in finally.

ReentrantLock.lock() waits to acquire; the owner can acquire again. ReentrantLock.getHoldCount() reports unmatched acquisitions by the current thread, not all threads. ReentrantLock.unlock() decrements the count and releases at zero; calling it from another thread throws IllegalMonitorStateException.

ReentrantLock.tryLock() immediately returns whether acquisition succeeded; success requires a later unlock(). The tryLock(long, TimeUnit) overload bounds waiting and can throw InterruptedException. new ReentrantLock(true) favors longest-waiting threads, but no-argument tryLock() ignores that policy.

ReentrantLock.newCondition() creates an associated Condition. For this lock, await() and signalling require ownership. await() releases it while waiting, then reacquires it and restores the hold count. Check the predicate in while because spurious wakeups are possible; a signal does not replace checking the state.

Examples

import java.util.concurrent.locks.ReentrantLock;

public class Main {
    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        lock.lock();
        try {
            System.out.println(lock.getHoldCount());
            if (lock.tryLock()) {
                try {
                    System.out.println(lock.getHoldCount());
                } finally {
                    lock.unlock();
                }
            }
            System.out.println(lock.getHoldCount());
        } finally {
            lock.unlock();
        }
        System.out.println(lock.getHoldCount());
    }
}

Result

1
2
1
0

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources