Skip to main content
Synchronization and locks · Topic 5 of 8

ReentrantLock

Definition​

ReentrantLock is an explicit lock you take with lock() and release in a finally block. Compared with synchronized it can also try for a lock without waiting (tryLock), give up after a timeout, and be interrupted while waiting.

Example code​

lock in try/finally, and tryLock

import java.util.concurrent.locks.ReentrantLock;

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

static void withdraw(int amount) {
lock.lock();
try { // always unlock in finally
if (amount <= balance) balance -= amount;
} finally {
lock.unlock();
}
}

public static void main(String[] args) throws InterruptedException {
withdraw(30);
System.out.println("balance: " + balance);

lock.lock(); // hold the lock in this thread
Thread other = new Thread(() -> {
boolean got = lock.tryLock(); // does not wait
System.out.println("other thread got the lock: " + got);
});
other.start();
other.join();
lock.unlock();
}
}

// Output:
// balance: 70
// other thread got the lock: false

Finished this page? Track your progress (saved only in your browser).