当前位置:网站首页>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
边栏推荐
- Appium inspector can directly locate the WebView page. Does anyone know the principle
- Ubuntu20.04 PostgreSQL 14 installation configuration record
- Recommend an online interface mock tool usemock
- matlab 使用 audioread 、 sound 读取和播放 wav 文件
- This is the form of the K-line diagram (pithy formula)
- uTools
- About asp Net core uses a small detail of datetime date type parameter
- Part 29 supplement (XXIX) basis of ECMAScript
- Daily work and study notes
- NeRV: Neural Reflectance and Visibility Fields for Relighting and View Synthesis
猜你喜欢
[IVX junior engineer training course 10 papers to get certificates] 09 chat room production
matlab 实现语音信号重采样和归一化,并播放比对效果
Matlab uses resample to complete resampling
Matlab uses audiorecorder and recordblocking to record sound, play to play sound, and audiobook to save sound
[Floyd] post disaster reconstruction
Docker installing Oracle_ 11g
Implementation of Weibo system based on SSM
Exclusive delivery of secret script move disassembly (the first time)
Introduction to ffmpeg Lib
This is the report that leaders like! Learn dynamic visual charts, promotion and salary increase are indispensable
随机推荐
站在新的角度来看待产业互联网,并且去寻求产业互联网的正确方式和方法
Liteos learning - first knowledge of development environment
SAP ui5 beginner tutorial 20 - explanation of expression binding usage of SAP ui5
Fastadmin controls the length of fields in the table
CTF daily question day45 sensor
[IVX junior engineer training course 10 papers to get certificates] 01 learn about IVX and complete the New Year greeting card
Three core problems of concurrent programming
CEPH buffer yyds dry inventory
matlab 使用 audioread 、 sound 读取和播放 wav 文件
The concept and application of Cartland number
[Floyd] post disaster reconstruction
A problem about function template specialization
Learning notes 25 - multi sensor front fusion technology
城市选择器组件实现原理
Quatre stratégies de base pour migrer la charge de travail de l'informatique en nuage
Implementation of Weibo system based on SSM
学习笔记2--高精度地图定义及价值
Based on Simulink and FlightGear, the dynamic control of multi rotor UAV in equilibrium is modeled and simulated
About asp Net core uses a small detail of datetime date type parameter
How does schedulerx help users solve the problem of distributed task scheduling?