Reputation: 1377
In the ducumentation of AQS, the first line says
Provides a framework for implementing blocking locks and related synchronizers (semaphores, events, etc) that rely on first-in-first-out (FIFO) wait queues.
Since AQS is based on FIFO wait queue, I think naturally is fair. But in the implementation of Samephore
and ReentrantLock
and many other place, there are both fair and unfair version of AQS.
So I want to know how AQS support unfair lock.
Alse to mention,I find those lines in the doc. But I clouldn't understand it. How does a thread barge ahead of others which are already in the queue?
Even though this class is based on an internal FIFO queue, it does not automatically enforce >FIFO acquisition policies. The core of exclusive synchronization takes the form:
Acquire: while (!tryAcquire(arg)) { enqueue thread if it is not already queued; possibly block current thread; }
Release: if (tryRelease(arg)) unblock the first queued thread;
(Shared mode is similar but may involve cascading signals.) Because checks in acquire are invoked before enqueuing, a newly acquiring thread may barge ahead of others that are blocked and queued.
Upvotes: 2
Views: 348
Reputation: 28269
How does a thread barge ahead of others which are already in the queue?
In the unfair mode, the new thread will try to take the lock first. If it fails, then it will be inserted into the queue.
Example:
Thread1 holds the lock;
Thread2 waits in the queue;
Thread1 releases the lock;
Almost the same time, Thread3 tries aquire the lock. When running in unfair mode, Thread3 is allowed to get the lock before Thread2 is notified . But in fair mode, Thread3 won't be allowed.
Thread3 releases the lock;
Thread2 gets the lock;
Upvotes: 1