Video in progress
How do the fair and non-fair modes of ReentrantLock differ, and which one would you pick?
A fair lock lets waiters through in queue order, while a non-fair lock lets a newly arrived thread "snatch" a lock that has just been released. Non-fair is usually much faster, and fair protects against starvation.
📖 Answer
Lock fast = new ReentrantLock(); // default: non-fair
Lock fair = new ReentrantLock(true); // fair
In non-fair mode, a thread that arrives just as the lock is released tries a CAS right away. If it succeeds, it doesn't wait for the queued threads to wake up. Waking a sleeping thread is expensive (a context switch), so this raises throughput noticeably.
In fair mode, every lock() first checks whether anyone is already in the queue. If so, it stands behind them. The result is that almost every handoff goes through a wakeup. It's normal for a fair lock to come out several times slower in benchmarks.
When you need fair:
- the lock is held for a long time and your metrics show that some threads never get a turn at all;
- an even response time matters more than average speed.
One catch: tryLock() (no arguments) breaks fairness even on a fair lock, because it grabs the lock regardless of the queue. If you need fairness, use tryLock(0, TimeUnit.SECONDS).
I usually start with non-fair and move to fair only when starvation is actually measured.
Sign up to mark studied questions and save your progress.