ReentrantLock Fair Acquisition Order

Construct ReentrantLock(true) so blocked workers are granted the lock in arrival order instead of letting later threads barge ahead.

JavaResilience

Code

snippet
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

public class FairLockAcquisitionOrder {

    public static void main(String[] args) throws InterruptedException {
        // true = 公平模式:锁按排队先后发放,先到先得
        ReentrantLock lock = new ReentrantLock(true);
        List<Thread> workers = new ArrayList<>();

        lock.lock(); // 主线程先占住锁,让三个 worker 依次入队
        try {
            for (int i = 1; i <= 3; i++) {
                Thread worker = new Thread(() -> {
                    lock.lock();
                    try {
                        System.out.println("granted to " + Thread.currentThread().getName());
                    } finally {
                        lock.unlock();
                    }
                }, "worker-" + i);
                worker.start();
                workers.add(worker);
                Thread.sleep(100); // 隔开启动时间,保证入队顺序与启动顺序一致
            }
        } finally {
            lock.unlock(); // 释放后公平锁按 FIFO 依次发放
        }

        for (Thread worker : workers) {
            worker.join();
        }
        System.out.println("isFair = " + lock.isFair());
    }
}

Inside the snippet

ReentrantLock Fair Acquisition Order reduces to the class FairLockAcquisitionOrder.

for (int i = 1; i <= 3; i++) carries the per-item work.

Watch out for

  • There is no dependency tree here — the platform is the whole dependency.

Putting it to use

Each stage prints its own label: granted to, isFair =.

Lines that carry the logic

Thread.sleep(100); // 隔开启动时间,保证入队顺序与启动顺序一致
}
List<Thread> workers = new ArrayList<>();
Thread worker = new Thread(() -> {
    lock.lock();
    try {
        System.out.println("granted to " + Thread.currentThread().getName());
    } finally {
        lock.unlock();
    }
}, "worker-" + i);

Interactive Tools for This Topic

FAQ

What does ReentrantLock Fair Acquisition Order print when run?
Invoke the file as-is — the `granted to`, `isFair =` prefixes identify which step printed each line.