Fair vs Unfair Locks
What you'll learn: How to use ReentrantLock with a fairness flag to prevent thread starvation by enforcing FIFO (first-in, first-out) lock acquisition order.
The Core Idea
You've learned that starvation occurs when some threads are repeatedly denied access to a lock. By default, Java's ReentrantLock is unfair—the scheduler can allow any waiting thread to acquire the lock, potentially letting aggressive or lucky threads jump ahead repeatedly.
A fair lock solves this by guaranteeing that threads acquire the lock in the order they requested it. Think of it like a deli counter: unfair locks let anyone grab a ticket and push to the front if the server isn't looking, while fair locks enforce strict queue discipline—first come, first served.
Fair ReentrantLock
ReentrantLock accepts a boolean fairness parameter:
// Unfair lock (default)
Lock unfairLock = new ReentrantLock();
// Fair lock - enforces FIFO ordering
Lock fairLock = new ReentrantLock(true);
With a fair lock, if Thread A requests the lock before Thread B, Thread A is guaranteed to acquire it first. This prevents starvation—every thread will eventually get its turn.
The Trade-off
Fair locks eliminate starvation but come at a cost: performance. Maintaining strict ordering requires more bookkeeping and context switches. Unfair locks achieve higher throughput because they allow opportunistic lock acquisition (reducing overhead), but risk starving unlucky threads.
Use fair locks when predictable, equitable access matters more than raw speed—for example, in systems where every request must be processed within reasonable time bounds.
Key Takeaway: ReentrantLock(true) creates a fair lock that prevents starvation by guaranteeing FIFO order, trading some performance for fairness and predictability.