AQS finishing of Java concurrency: why use AQS, AQS core code flow

1、AQS

1.1 What is AQS? Why use AQS?

AQS (Abstract Queued Synchronizer): The abstract queue synchronizer is a locking mechanism other than the synchronized keyword that comes with java.

Java already provides synchronized locks at the language level, why provide AQS locks at the SDK level? If the performance of synchronized is not as good as AQS before 1.6, but after 1.6, synchronized has already done lock upgrade, so why continue to use AQS? Because AQS provides the following solutions that cannot be realized by synchronized:

  • Ability to set timeout
  • non-blocking lock acquisition
  • able to respond to interrupts

1.2 General principle of AQS

The core idea of ​​AQS is: if the requested shared resource is idle, the thread currently requesting the resource is set as an effective worker thread, and the shared resource is set to a locked state. If the requested shared resource is occupied, then 需要一套线程阻塞等待以及被唤醒时锁分配的机制, this mechanism, AQS是用CLH队列锁实现的,即将暂时获取不到锁的线程加入到队列中.

The CLH (Craig, Landin, and Hagersten) queue is a virtual two-way queue. In a virtual two-way queue, there is no queue instance, but only the association relationship between nodes.

AQS encapsulates each thread requesting shared resources into a node (Node) of a CLH lock queue to realize lock allocation.

In plain language: AQS is based on the CLH queue, and the shared variable state is modified with volatile. The thread changes the status symbol through CAS. If it succeeds, it acquires the lock. If it fails, it enters the waiting queue and waits to be woken up.

insert image description here

AQS defines two resource sharing methods :
1. Exclusive: Exclusive, only one thread can execute, such as ReentrantLock
2.Share: Shared, multiple threads can execute at the same time, such as Semaphore, CountDownLatch, ReadWriteLock, CyclicBarrier

1.3 The core code flow of AQS

Next, ReentrantLock is used to analyze how AQS manages resource usage in multi-threaded situations. The core code flow is shown in the figure below.

There are many contents, you can click on the larger image to view:
insert image description here

Guess you like

Origin blog.csdn.net/xueping_wu/article/details/126558076
AQS
AQS