tryLock, timeouts and fair locks
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)lock() and synchronized have one choice when the lock is busy: wait, for as long as it takes. A ReentrantLock gives three more choices: do not wait at all, wait only for a limited time, or wait until someone cancels you.
tryLock() without waiting
tryLock() is a Lock method that takes the lock only if it is free and returns true. If another thread holds the lock, it returns false at once instead of waiting.
tryLock() takes the lock only if it is free at this moment and returns true. If another thread holds it, it returns false at once and the thread does not wait.
if (lock.tryLock()) { try { // got the lock: do the work } finally { lock.unlock(); }} else { // lock was busy: skip, retry later or tell the user}Use it when the work can be skipped or done later: a printer that is busy, a report that someone else is already building. Your code must check the result and call unlock() only when it was true.
Example 1 · tryLock(): the library printer is busy
import java.util.concurrent.locks.ReentrantLock;
public class TryLockDemo { static final ReentrantLock printer = new ReentrantLock();
static void printNotes(String student) { if (printer.tryLock()) { try { System.out.println(student + ": printing notes"); } finally { printer.unlock(); } } else { System.out.println(student + ": printer busy, will try later"); } }
public static void main(String[] args) throws InterruptedException { printNotes("Asha"); // printer is free
printer.lock(); // main is now using the printer try { Thread ravi = new Thread(() -> printNotes("Ravi"), "ravi"); ravi.start(); ravi.join(); } finally { printer.unlock(); }
Thread meena = new Thread(() -> printNotes("Meena"), "meena"); meena.start(); meena.join(); }}Asha: printing notes Ravi: printer busy, will try later Meena: printing notes
What this code does
- Asha finds the printer free, so
tryLock()returnstrueand she prints. - While
mainholds the lock,tryLock()in theravithread returnsfalseimmediately. Ravi does not wait; he gets a message. - After
mainunlocks, Meena'stryLock()succeeds.unlock()is called only on thetruebranch.
Predict the output
What does tryLock() return?
Read the code and pick what it prints.
Round 1 of 2
What does this program print?
tryLock with a timeout
tryLock(time, unit) waits for the lock, but only up to the given time. It returns true if it got the lock in time, and false if the time ran out. TimeUnit (in java.util.concurrent) names the unit, such as TimeUnit.MILLISECONDS.
Example 2 · Cinema seats: wait a little, then give up
import java.util.concurrent.TimeUnit;import java.util.concurrent.locks.ReentrantLock;
class SeatMap { final ReentrantLock lock = new ReentrantLock();
String tryBook(String user, long waitMs) throws InterruptedException { if (lock.tryLock(waitMs, TimeUnit.MILLISECONDS)) { try { return user + ": seat locked, booking done"; } finally { lock.unlock(); } } return user + ": gave up after " + waitMs + " ms, please try again"; }}
public class TryLockTimeoutDemo { public static void main(String[] args) throws InterruptedException { SeatMap seats = new SeatMap(); String[] results = new String[2];
Thread quick = new Thread(() -> { try { results[0] = seats.tryBook("Kiran", 50); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }, "kiran"); Thread patient = new Thread(() -> { try { results[1] = seats.tryBook("Divya", 1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }, "divya");
seats.lock.lock(); // another booking holds the seat map try { quick.start(); quick.join(); // Kiran gives up while the lock is still held patient.start(); while (!seats.lock.hasQueuedThread(patient)) { Thread.sleep(1); // wait until Divya is waiting for the lock } } finally { seats.lock.unlock(); } patient.join(); System.out.println(results[0]); System.out.println(results[1]); }}Kiran: gave up after 50 ms, please try again Divya: seat locked, booking done
What this code does
mainkeeps holding the lock until Kiran's thread has finished. Kiran is willing to wait only 50 ms, so histryLockreturnsfalseand he gets a "try again" message.- Divya waits up to 1000 ms. As soon as she is in the queue,
mainreleases the lock, so hertryLockreturnstruelong before her limit. join()and the queue check fix the order of events, and results are printed afterjoin(), so the output is the same on every run.
This is the usual way to make sure a thread never waits forever. A booking page can wait a moment for the seat lock, then show "Please try again" instead of freezing. While it waits, the thread can be interrupted, so this method throws the checked InterruptedException.
lockInterruptibly()
lockInterruptibly() waits for the lock like lock(), but it stops waiting if the thread is interrupted and throws InterruptedException. That lets another thread cancel a task that is stuck waiting.
Example 3 · lockInterruptibly() can be cancelled, lock() cannot
import java.util.concurrent.locks.ReentrantLock;
public class InterruptibleLockDemo { static final ReentrantLock paymentLock = new ReentrantLock();
public static void main(String[] args) throws InterruptedException { Thread rahul = new Thread(() -> { try { paymentLock.lockInterruptibly(); try { System.out.println("rahul: paying"); } finally { paymentLock.unlock(); } } catch (InterruptedException e) { System.out.println("rahul: interrupted while waiting, payment cancelled"); } }, "rahul");
Thread priya = new Thread(() -> { paymentLock.lock(); // ignores interrupts while waiting try { System.out.println("priya: got the lock, interrupted flag = " + Thread.currentThread().isInterrupted()); } finally { paymentLock.unlock(); } }, "priya");
paymentLock.lock(); // main keeps the payment lock busy try { rahul.start(); priya.start(); while (paymentLock.getQueueLength() < 2) { // wait until both are waiting Thread.sleep(1); } rahul.interrupt(); priya.interrupt(); rahul.join(); System.out.println("priya still waiting? " + paymentLock.hasQueuedThread(priya)); } finally { paymentLock.unlock(); } priya.join(); }}rahul: interrupted while waiting, payment cancelled priya still waiting? true priya: got the lock, interrupted flag = true
What this code does
- Both threads wait while
mainholds the lock, andmaininterrupts both. Rahul usedlockInterruptibly(), so he stops waiting at once and his payment is cancelled. - Priya used
lock(), so the interrupt does not stop her. She keeps waiting, gets the lock whenmainreleases it, and only then sees that her interrupt flag is set. - Use
lockInterruptibly()when a waiting task must be cancellable, for example when a user closes the page.
Plain lock() ignores interrupts while it waits. The thread keeps waiting until it gets the lock, and only its interrupt flag is set. synchronized behaves the same way: a thread blocked on a monitor cannot be interrupted.
InterruptedException and cannot pass it on, restore the flag with Thread.currentThread().interrupt(), as in the Thread Basics module.Fair versus unfair locks
A fair lock, created with new ReentrantLock(true), gives the lock to the thread that has waited longest, roughly in queue order. The default, new ReentrantLock(), is unfair: a thread that asks at the right moment may grab the lock ahead of the waiting threads.
Example 4 · Unfair versus fair: who gets the lock next
import java.util.concurrent.locks.ReentrantLock;
public class FairnessDemo { static String run(boolean fair) throws InterruptedException { ReentrantLock lock = new ReentrantLock(fair); StringBuilder order = new StringBuilder(); Runnable task = () -> { String me = Thread.currentThread().getName(); for (int i = 0; i < 6; i++) { lock.lock(); try { order.append(me); Thread.sleep(2); // a little work while holding the lock } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { lock.unlock(); } } }; Thread a = new Thread(task, "A"); Thread b = new Thread(task, "B"); lock.lock(); try { a.start(); b.start(); while (lock.getQueueLength() < 2) { // wait until both are queued Thread.sleep(1); } } finally { lock.unlock(); } a.join(); b.join(); return order.toString(); }
public static void main(String[] args) throws InterruptedException { System.out.println("Unfair lock: " + run(false)); System.out.println("Fair lock: " + run(true)); }}Unfair lock: AAAAAABBBBBB Fair lock: ABABABABABAB
What this code does
- With the unfair lock, the thread that just unlocked usually grabs the lock again before the sleeping waiter wakes up, so one thread runs all six turns first. Which letter goes first changes from run to run.
- With the fair lock, the waiting thread is first in the queue, so the two threads take turns.
- The exact strings depend on timing and are not guaranteed, but this pattern shows up on most runs.
Jumping the queue like this is called barging. Unfair locks are usually faster: the thread that just released the lock is often still running and can take it again at once, while waking a sleeping waiter takes time. The cost is that one thread can sometimes wait much longer than the others.
A fair lock prevents a waiter from being skipped forever (starvation), but it is noticeably slower when many threads compete. Use it only when that matters. Note that plain tryLock() ignores fairness: it grabs a free lock even if others are waiting.
Next step
Check your understanding
11 quick questions