Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Lock — explicit lock acquisition and release

The java.util.concurrent.locks.Lock interface provides explicit control over locking. Learn the lock()/unlock() pair, the safe try/finally pattern, and an example using ReentrantLock to protect a shared counter.

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

Syntax

Lock lock = new ReentrantLock();
lock.lock();
try {
    // protected operations
} finally {
    lock.unlock();
}

java.util.concurrent.locks.Lock is an interface for explicit locking; ReentrantLock is an implementation providing mutual exclusion and reentry by the same thread. Not every Lock implementation must have these properties.

Lock.lock() acquires the lock, waiting if necessary; Lock.unlock() releases it. Call lock.lock() before try, and lock.unlock() in finally. Unlike synchronized, release is not automatic. finally ensures release even after an exception in the protected code.

All competing accesses to protected state must follow the same locking protocol. A successful acquisition by a thread that does not already hold the lock and a successful full release have the same memory synchronization effects as acquiring and releasing a monitor, respectively. Lock does not require memory synchronization effects for unsuccessful operations or for reentrant acquisitions and their matching releases. synchronized (lock) does not replace lock.lock().

With ReentrantLock, each acquisition needs a matching release; unlock() by a thread that does not hold the lock throws IllegalMonitorStateException. The interface also offers tryLock() and lockInterruptibly() for other waiting strategies.

The example uses one shared lock for both count++ operations. After both join() calls, the program prints 2 regardless of thread execution order. Documentation scope: Java SE 21; repository runtime and production runtime are not attested.

Examples

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Main {
    private static final Lock lock = new ReentrantLock();
    private static int count = 0;

    private static void increment() {
        lock.lock();
        try {
            count++;
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread first = new Thread(Main::increment);
        Thread second = new Thread(Main::increment);
        first.start();
        second.start();
        first.join();
        second.join();
        System.out.println(count);
    }
}

Result

2

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