简体   繁体   English

java AQS 如何支持不公平锁?

[英]How does java AQS support unfair lock?

In the ducumentation of AQS, the first line says在AQS的文件中,第一行说

Provides a framework for implementing blocking locks and related synchronizers (semaphores, events, etc) that rely on first-in-first-out (FIFO) wait queues.提供一个框架,用于实现依赖先进先出 (FIFO) 等待队列的阻塞锁和相关同步器(信号量、事件等)。

Since AQS is based on FIFO wait queue, I think naturally is fair.既然AQS是基于FIFO等待队列的,我觉得自然是公平的。 But in the implementation of Samephore and ReentrantLock and many other place, there are both fair and unfair version of AQS.但是在SamephoreReentrantLock等很多地方的实现中,AQS的版本有公平也有不公平。

So I want to know how AQS support unfair lock.所以我想知道AQS是如何支持不公平锁的。

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.即使此类基于内部 FIFO 队列,它也不会自动执行 >FIFO 采集策略。 The core of exclusive synchronization takes the form:独占同步的核心形式为:

Acquire: while (!tryAcquire(arg)) { enqueue thread if it is not already queued;获取:while (!tryAcquire(arg)) { 如果线程尚未排队,则将其加入队列; possibly block current thread;可能阻塞当前线程; } }

Release: if (tryRelease(arg)) unblock the first queued thread;释放: if (tryRelease(arg)) 解除第一个排队线程的阻塞;

(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. (共享模式是类似的,但可能涉及级联信号。)因为在入队之前调用获取中的检查,新的获取线程可能会抢在其他被阻塞和排队的线程之前。

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:例子:

  1. Thread1 holds the lock; Thread1 持有锁;

  2. Thread2 waits in the queue; Thread2 在队列中等待;

  3. Thread1 releases the lock; Thread1 释放锁;

  4. Almost the same time, Thread3 tries aquire the lock.几乎同时,Thread3 尝试获取锁。 When running in unfair mode, Thread3 is allowed to get the lock before Thread2 is notified .在不公平模式下运行时,允许 Thread3 在通知 Thread2 之前获得锁。 But in fair mode, Thread3 won't be allowed.但在公平模式下,Thread3 将不被允许。

  5. Thread3 releases the lock; Thread3 释放锁;

  6. Thread2 gets the lock; Thread2 获得锁;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM