Master Java ReentrantLock: Simple Thread‑Safe Coding Without synchronized

This article introduces Java's ReentrantLock as an easy-to‑use alternative to synchronized, explains its core lock() and unlock() methods, demonstrates practical code examples, and covers advanced APIs such as tryLock, getQueueLength, isLocked, and getHoldCount for robust multithreaded programming.

FunTester
FunTester
FunTester
Master Java ReentrantLock: Simple Thread‑Safe Coding Without synchronized

When learning Java, multithreading is an essential advanced topic, and the ReentrantLock class offers the simplest way to achieve thread safety without the verbosity of synchronized.

The article references earlier posts on other synchronization utilities such as CountDownLatch, CyclicBarrier, Phaser, and the classic "three swordsmen" of Java thread synchronization. ReentrantLock mainly provides two methods: lock() to acquire the lock and unlock() to release it. All thread‑safe operations should be placed between these calls, similar to using a Semaphore with a single permit.

Below is a basic usage example that demonstrates acquiring the lock in an asynchronous task, printing messages, and releasing the lock, followed by the main thread performing the same steps:

public static void main(String[] args) {
    ReentrantLock lock = new ReentrantLock();
    fun(() -> {
        lock.lock();
        output("FunTester获取锁了");
        sleep(2.0);
        lock.unlock();
        output("FunTester释放锁了");
        return null;
    });
    sleep(1.0);
    lock.lock();
    output("main线程获取锁");
    lock.unlock();
    output("main线程释放锁");
}

The console output shows the order of lock acquisition and release for both the asynchronous task and the main thread.

Because an exception may prevent unlock() from executing, it is recommended to place the unlock call inside a finally block.

Beyond the basic methods, ReentrantLock offers several less‑common APIs: boolean tryLock(long timeout, TimeUnit unit) – attempts to acquire the lock within a specified timeout. int getQueueLength() – returns an approximate number of threads waiting for the lock. boolean isLocked() – checks whether the lock is currently held. int getHoldCount() – returns the number of holds by the current thread, reflecting the re‑entrancy count.

These additional methods can help handle advanced scenarios such as timed lock acquisition, monitoring contention, and debugging re‑entrant behavior.

The java.util.concurrent package is a treasure trove for Java developers, and exploring its source code can deepen understanding of concurrency mechanisms.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendJavaconcurrencythread safetyReentrantLock
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.