Java

ReentrantLock — Beyond synchronized

admin by @admin ADMIN
Jun 18, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`ReentrantLock` does what `synchronized` does, plus: tryLock with timeout, fair queueing, interruptible acquire, multiple condition variables. Use when synchronized's rigidity bites.
Java
Raw
import java.util.concurrent.locks.*;
import java.util.concurrent.*;

class Demo {
    private final ReentrantLock lock = new ReentrantLock();
    private int balance = 100;

    boolean withdraw(int amount) {
        lock.lock();                                 // blocks if held
        try {
            if (balance < amount) return false;
            balance -= amount;
            return true;
        } finally {
            lock.unlock();                           // ALWAYS unlock in finally
        }
    }

    // tryLock with timeout — bail out rather than block forever
    boolean tryWithdraw(int amount, long ms) throws InterruptedException {
        if (!lock.tryLock(ms, TimeUnit.MILLISECONDS)) return false;
        try {
            if (balance < amount) return false;
            balance -= amount;
            return true;
        } finally {
            lock.unlock();
        }
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.