Locks, conditions and AQS question 36 of 180 mid
What does a fair lock actually do, and what does it cost?
- It gives every thread equal CPU time
- Correct: It hands the lock to the longest-waiting thread instead of whoever asks first, which removes barging and costs a great deal of throughput
- It prevents deadlock
- It is the default for
ReentrantLock
An unfair lock lets an arriving thread barge: if the lock is free at the moment it asks, it takes it, even though others have been queued for a while. That is fast, because the running thread is already on a CPU with warm caches and no context switch is needed.
A fair lock checks the queue first and always yields to the longest waiter. Every handoff then costs a park and an unpark. Throughput typically drops by an order of magnitude under contention.
Unfair is the default, and usually right. Choose fairness when starvation is a real risk and hold
times are long enough that the handoff cost does not dominate. Note what fairness does not promise:
the scheduler still decides who runs, and tryLock() barges even on a fair lock, by design.
Quiz yourself on Locks, conditions and AQS Suggest a correction