当前位置:网站首页>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
边栏推荐
- Recommend an online interface mock tool usemock
- Look at the industrial Internet from a new perspective and seek the correct ways and methods of industrial Internet
- Implementation of Weibo system based on SSM
- Edge computing accelerates live video scenes: clearer, smoother, and more real-time
- Pyldavis installation and use | attributeerror: module 'pyldavis' has no attribute' gensim '| visual results are exported as separate web pages
- 游戏思考15:全区全服和分区分服的思考
- Six lessons to be learned for the successful implementation of edge coding
- matlab 实现语音信号重采样和归一化,并播放比对效果
- Convolutional neural network (including code and corresponding diagram)
- 三分钟学会基础k线图知识
猜你喜欢

Matlab uses audioread and sound to read and play WAV files

Feature extraction and detection 16 brisk feature detection and matching

GL Studio 5 installation and experience

【疾病检测】基于BP神经网络实现肺癌检测系统含GUI界面

Learning note 3 -- Key Technologies of high-precision map (Part 1)

What are the affordable Bluetooth headsets? Student party parity Bluetooth headset recommendation

Leetcode, 3 repeatless longest subsequence

Pyldavis installation and use | attributeerror: module 'pyldavis' has no attribute' gensim '| visual results are exported as separate web pages

Liteos learning - first knowledge of development environment

The first "mobile cloud Cup" empty publicity meeting, looking forward to working with developers to create a new world of computing!
随机推荐
The role of artificial intelligence in network security
Leetcode 45 Jumping game II (2022.02.14)
Bat Android Engineer interview process analysis + restore the most authentic and complete first-line company interview questions
Principle of finding combinatorial number and template code
The concept and application of Cartland number
2022年6月国产数据库大事记
站在新的角度来看待产业互联网,并且去寻求产业互联网的正确方式和方法
Basic usage of three JS high-order functions --filter---map---reduce
What is commercial endowment insurance? Is commercial endowment insurance safe?
Design and implementation of radio energy transmission system
Sql--- related transactions
学习笔记3--高精度地图关键技术(上)
开发那些事儿:如何利用Go单例模式保障流媒体高并发的安全性?
[image enhancement] vascular image enhancement based on frangi filter with matlab code
现货黄金分析的技巧有什么呢?
6-2 vulnerability exploitation - inevitable problems of FTP
SAP ui5 beginner tutorial XXI - trial version of custom formatter of SAP ui5
Day 13 of hcip (relevant contents of BGP agreement)
Design and control of multi rotor aircraft (VII) -- sensor calibration and measurement model
Exclusive delivery of secret script move disassembly (the first time)