当前位置:网站首页>What is AQS and its principle
What is AQS and its principle
2022-07-02 01:34:00 【Ysming88】
On Concurrency , I have to talk about it ReentrantLock; And when it comes to ReentrantLock, I have to talk about it AbstractQueuedSynchronizer(AQS)!
Like its name , Abstract queue synchronizer ,AQS A set of synchronizer framework for multi thread access to shared resources is defined , Many synchronous class implementations depend on it , As in common use ReentrantLock、Semaphore、CountDownLatch...
1、AQS brief introduction
AQS full name :AbstractQueuedSynchronizer, It's a concurrency container J.U.C(java.util.concurrent) Next locks A class in the package . It implements a FIFO(FirstIn、FisrtOut fifo ) Queues . The underlying data structure is a two-way linked list .CLH(Craig,Landin,and Hagersten) A queue is a virtual two-way queue ( Virtual two-way queue means there is no queue instance , There is only an association between nodes ).AQS It is to encapsulate each thread requesting shared resources into a CLH A node in a lock queue (Node) To achieve lock allocation , I'll talk about it later .
It maintains a volatile int state( On behalf of shared resources ) And a FIFO Thread wait queue ( Multithreaded contention resources will enter this queue when they are blocked ). here volatile It's the core keyword , Specifically volatile The semantics of the , I won't talk about it here .state There are three ways to visit :
- getState()
- setState()
- compareAndSetState()
AQS Two resource sharing methods are defined :
Exclusive( Monopoly ): Only one thread can execute , Such as ReentrantLock. It can be divided into fair lock and unfair lock :
- Fair lock : In the order in which threads are queued in the queue , First come, first get the lock
- Not fair lock : When a thread wants to acquire a lock , Ignore the queue order and grab the lock directly , Whoever steals it is his
Share( share ): Multiple threads can execute at the same time , Such as Semaphore/CountDownLatch.
Different synchronizers compete for shared resources in different ways . The synchronizer only needs to realize shared resources state How to obtain and release , As for the maintenance of specific thread waiting queue ( If you fail to get resources and join the team / Wake up and wait ),AQS It has been implemented at the top level . The synchronizer mainly realizes the following methods :
- isHeldExclusively(): In exclusive mode , Is the thread exclusive of resources .
Exclusive way :
- tryAcquire(int): Try to get resources , Return on success true, Failure returns false.
- tryRelease(int): Try to free resources , Return on success true, Failure returns false.
How to share :
- tryAcquireShared(int): Try to get resources . A negative number means failure ;0 It means success , But there are no remaining resources available ; A positive number means success , And there are surplus resources .
- tryReleaseShared(int): Try to free resources , If it is allowed to wake up after release and wait for the node to return true, Otherwise return to false.
With ReentrantLock For example ,state Initialize to 0, Indicates unlocked state .A Threads lock() when , Would call tryAcquire() Monopolize the lock and state+1. thereafter , Other threads tryAcquire() It's going to fail , until A Threads unlock() To state=0( Release the lock ) until , Other threads have the chance to acquire the lock . Of course , Before releasing the lock ,A The thread itself can acquire the lock repeatedly (state Will accumulate ), This is the concept of reentry . But should pay attention to , How many times to get, how many times to release , In this way, we can guarantee state Can go back to zero .
And then to CountDownLatch For example , The task is divided into N Sub thread to execute ,state Also initialized to N( Be careful N Be consistent with the number of threads ). this N Subthreads are executed in parallel , After the execution of each sub thread countDown() once ,state Meeting CAS reduce 1. Wait until all the sub threads are finished ( namely state=0), Meeting unpark() Main calling thread , Then the main calling thread will start from await() The function returns , Continue the rest of the action .
Generally speaking , Synchronizer is either an exclusive method , Or sharing , They just need to achieve tryAcquire-tryRelease or tryAcquireShared-tryReleaseShared One of them is enough . but AQS It also supports synchronizer to realize exclusive and sharing at the same time , Such as ReentrantReadWriteLock.
Recommended reference blog :Java And contract the cornerstone -AQS Detailed explanation
Java Concurrent AQS Detailed explanation
What is? AQS And its principle
边栏推荐
- Brief introduction to the development of mobile network
- [IVX junior engineer training course 10 papers] 04 canvas and a group photo of IVX and me
- GL Studio 5 安装与体验
- Luogu p1775 stone merger (weakened version)
- The technology boss is ready, and the topic of position C is up to you
- Error creating bean with name ‘stringRedisTemplate‘ defined in class path re
- 并发编程的三大核心问题
- 2022年6月国产数据库大事记
- 首场“移动云杯”空宣会,期待与开发者一起共创算网新世界!
- Feature extraction and detection 16 brisk feature detection and matching
猜你喜欢
Matlab uses audioread and sound to read and play WAV files
Finally got byte offer, 25-year-old inexperienced experience in software testing, to share with you
Learning note 24 - multi sensor post fusion technology
[Floyd] post disaster reconstruction
迁移云计算工作负载的四个基本策略
Pyldavis installation and use | attributeerror: module 'pyldavis' has no attribute' gensim '| visual results are exported as separate web pages
Based on Simulink and FlightGear, the dynamic control of multi rotor UAV in equilibrium is modeled and simulated
[IVX junior engineer training course 10 papers to get certificates] 03 events and guessing numbers games
MATLAB realizes voice signal resampling and normalization, and plays the comparison effect
Six lessons to be learned for the successful implementation of edge coding
随机推荐
Luogu p1775 stone merger (weakened version)
首场“移动云杯”空宣会,期待与开发者一起共创算网新世界!
Study note 2 -- definition and value of high-precision map
Have you stepped on the nine common pits in the e-commerce system?
How can I batch produce the same title for the video?
电子协会 C语言 1级 32、计算2的幂
Learning note 3 -- Key Technologies of high-precision map (Part 1)
10 minutes to get started quickly composition API (setup syntax sugar writing method)
技术大佬准备就绪,话题C位由你决定
Exclusive delivery of secret script move disassembly (the first time)
Develop those things: how to use go singleton mode to ensure the security of high concurrency of streaming media?
The concept and application of Cartland number
城市选择器组件实现原理
[IVX junior engineer training course 10 papers to get certificates] 09 chat room production
Edge computing accelerates live video scenes: clearer, smoother, and more real-time
error: . repo/manifests/: contains uncommitted changes
6-3漏洞利用-SSH环境搭建
Error creating bean with name ‘stringRedisTemplate‘ defined in class path re
Four basic strategies for migrating cloud computing workloads
Hcip day 14 (MPLS protocol)