AQS(AbstractQueuedSynchronizer
)这个类提供了一个框架用来实现阻塞锁和一些同步工具类。比如ReentrantLock
、ReadWriteLock
、Semaphore
、CountDownLatch
、CyclicBarrier
等。
AQS
1 | public abstract class AbstractQueuedSynchronizer |
介绍
这个类通过维护一个volatile
修饰的变量state
表示锁的获取情况以及一个FIFO队列用来封装要阻塞的线程。
线程通过CAS来修改state
来获取锁,如果获取失败,会将当前线程封装成队列节点入队或者返回失败(tryLock()
)。
1 | while(synchronization state does not allow acquire){ |
队列中的每个节点都封装了一个没有获取到锁而被阻塞的线程,队列中的节点有多种状态,比如SIGNAL代表当前节点的后继节点被阻塞了,当释放锁时需要唤醒后继节点中的线程。CANCELLED
表示当前节点中的线程超时或者被中断了,此时就会将节点的waitStatus
改为CANCELLED
。保证出队和入队线程安全用的锁是CLH锁,CLH是一种基于链表的高性能自旋锁。作者介绍说CLH锁相对于MCS锁比较容易处理节点的超时和取消状态。并且出队和入队由于没有锁操作,效率会更高一些。
However, they appeared more amenable than MCS for use in the synchronizer framework because they are more easily adapted to handle cancellation and timeouts, so were chosen as a basis.
Among the advantages of CLH locks are that enqueuing and dequeuing are fast, lock-free, and obstruction free (even under contention, one thread will always win an insertion race so will make progress); that detecting whether any threads are waiting is also fast (just check if head is the same as tail); and that release status is decentralized, avoiding some memory contention
1 | /** |