当前位置:网站首页>AQS principle
AQS principle
2022-07-29 00:49:00 【51CTO】
AQS principle
1. summary
The full name is AbstractQueuedSynchronizer, yes Framework for blocking locks and associated synchronizer tools . Subclasses inherit it to implement synchronizers . The underlying implementation can refer to Monitor understand . Mainly through CAS and volitile maintain state So as to realize the lock of .

Source code display :

characteristic :
AQS It's an abstract class .AQS And its implementation class , Be similar to Monitor. Look at the second and third items below . however Monitor It's invisible , It's provided by the operating system .AQS yes Java adopt CAS and volitile The implementation is similar to Monitor The synchronizer .
- use state Property to represent the state of the resource ( It can be divided into exclusive mode and shared mode ), Subclasses need to define how to maintain this state , Controls how locks are acquired and released

- getState - obtain state state
- setState - Set up state state
- compareAndSetState - cas Mechanism settings state state
- Exclusive mode is that only one thread can access the resource , Shared mode allows multiple threads to access resources
- Provides the basis for FIFO Wait queue to achieve blocking queue , Be similar to Monitor Of EntryList. There is one Node Inner class , Used to implement FIFO Waiting queue . Later on ReentrantLock When implementing the principle , Will introduce in detail .
- Conditional variables to achieve waiting 、 Wake up mechanism , Support multiple conditional variables , Be similar to Monitor Of WaitSet. Use Lock.newCondition() Generate condition variables , The synchronizer is used at the bottom ( namely AQS Implementation class of ) newly build .

AQS Conditional variables in class

Subclasses mainly implement such methods ( Default throw UnsupportedOperationException)
- tryAcquire
- tryRelease
- tryAcquireShared
- tryReleaseShared
- isHeldExclusively
Get lock and release lock . Later on ReentrantLock When implementing the principle , Will introduce in detail .
Get lock pose
// If the lock acquisition fails
if (!tryAcquire(arg)) {
// The team , You can choose to block the current thread park unpark
}
Release lock posture
// If the lock is released successfully
if (tryRelease(arg)) {
// Let the blocked thread run again
}
2. Implement non reentrant locks
Custom synchronizer

Custom Lock
With a custom synchronizer , It's easy to reuse AQS , Implement a fully functional Custom Lock .
according to lock Method we can see the synchronizer sync amount to monitor, Similar to monitor Of EntryList Waiting queue .
test :
NonfairSync Inherited from AQS. Let's take a look , More on that later .

Output :
22:29:28.727 c.TestAqs [t1] - locking...
22:29:29.732 c.TestAqs [t1] - unlocking...
22:29:29.732 c.TestAqs [t2] - locking...
22:29:29.732 c.TestAqs [t2] - unlocking...
Non reentrant test
If you change to the following code , You will find yourself blocked ( Only print once locking)
lock.lock();
log.debug("locking...");
lock.lock();
log.debug("locking...");
3. Experience
origin
Early programmers would use one synchronizer to implement another similar synchronizer , For example, a reentrant lock is used to implement a semaphore , Or vice versa . It's obviously not elegant enough , therefore stay JSR166(java Specification proposal ) Created in AQS, This general synchronizer mechanism is provided .
The goal is
AQS Functional objectives to be achieved
- Blocking version acquisition lock acquire And non blocking versions try to get locks tryAcquire( If the attempt fails, it will not enter the waiting queue )
- Get lock timeout mechanism
- By interrupting the cancellation mechanism
- Exclusive mechanism and sharing mechanism
- Waiting mechanism when conditions are not met
Performance goals to achieve
Instead, the primary performance goal here is scalability: to predictably maintain efficiency even, or especially, when synchronizers are contended
contrary , The main performance goal here is scalability : When competing for synchronizer , Maintain efficiency predictably .
Design
AQS The basic idea of is actually very simple
The logic of acquiring lock
while(state Status does not allow getting ) {
if( This thread is not in the queue yet ) {
Join the team and block
}
}
The current thread is out of the queue
Logic of releasing lock
if(state Status allows ) {
Recover blocked threads (s)
}unpark Indicates to wake up the next thread . I'll give you a detailed introduction later .
The main points of
● Atomic maintenance state state ( adopt CAS and volitile)
● Blocking and resuming threads
● Maintenance queue
1) state Design
- state Use volatile coordination cas Ensure the atomicity of its modification .
- state Used 32bit int To maintain the synchronization state , Because... Was used long The test results on many platforms are not ideal .
2) Blocking recovery design
- Early control threads pause and resume api Yes suspend and resume, But they are not available , Because if you call first resume, that suspend Will not feel
- The solution is to use park & unpark To pause and resume threads , The specific principle has been mentioned before , First unpark Again park Also no problem
- park & unpark It's about threads , Not for the synchronizer , Therefore, the control granularity is more fine
- park Threads can also pass through interrupt interrupt
3) Queue design
- Used FIFO First in, first out , To realize the waiting queue ( Be similar to Monitor Of EntryList) And conditional variables . Priority queues are not supported .
- The design draws on CLH( Synchronous queue ) queue , It is a one-way lockless queue .
In the queue head and tail Two pointer nodes , Use both volatile Decorate with cas Use , Every Node Yes state Maintain node status .
After joining and leaving the team, we will introduce in detail .
Queue pseudo code , Just think about it tail Atomicity of assignment .

Outgoing pseudo code

CLH benefits :
- unlocked , Use spin
- Fast , Non blocking
AQS Improved in some ways CLH
Mainly used AQS Concurrency tool class

边栏推荐
- 【愚公系列】2022年07月 Go教学课程 020-Go容器之数组
- DRF - web development mode, API interface, API interface testing tool, restful specification, serialization and deserialization, DRF installation and use
- selenium对接代理与seleniumwire访问开发者工具NetWork
- “吃货联盟定餐系统”
- PTA (one question per day) 7-76 ratio
- AQS原理
- Outlier detection and Gan network (1)
- I don't know how lucky the boy who randomly typed the log is. There must be a lot of overtime!
- Api 接口优化的那些技巧
- Anomaly detection and unsupervised learning (1)
猜你喜欢
![[development tutorial 11] crazy shell · open source Bluetooth heart rate waterproof sports Bracelet - explanation of the function code of the whole machine](/img/a1/9a69e5d123a8a11504da251bd1bcfc.png)
[development tutorial 11] crazy shell · open source Bluetooth heart rate waterproof sports Bracelet - explanation of the function code of the whole machine

Api 接口优化有哪些技巧?

"Food alliance ordering system"
![[basic course of flight control development 8] crazy shell · open source formation uav-i2c (laser ranging)](/img/0b/d6defd524f83e69b40b5878ffe2e3c.png)
[basic course of flight control development 8] crazy shell · open source formation uav-i2c (laser ranging)
![[micro services ~nacos] Nacos service providers and service consumers](/img/b7/47ecd6979ccfeb270261681d6130be.png)
[micro services ~nacos] Nacos service providers and service consumers

从零开始实现lmax-Disruptor队列(六)Disruptor 解决伪共享、消费者优雅停止实现原理解析

时间序列数据的预处理方法总结

JWT token related configuration (global configuration identity authentication rewrites authenticate method)

Statistical analysis of time series

PTA (daily question) 7-69 narcissus number
随机推荐
SurfaceControl和SurfaceFlinger通信
PTA (daily question) 7-70 diamond
R语言怎么学
ZABBIX deployment and monitoring
【MySQL 8】Generated Invisible Primary Keys(GIPK)
华为发布HarmonyOS 3.0,向“万物互联”再迈一步
Some operations of Ubuntu remote server configuration database (unable to locate package MySQL server, steps of installing mysql, unable to enter password when logging in MySQL)
15.模型评估和选择问题
DRF -- authentication, authority, frequency source code analysis, global exception handling, automatic generation of interface documents, RBAC introduction
最长上升子序列
【开发教程10】疯壳·开源蓝牙心率防水运动手环-蓝牙 BLE 收发
Matlab02: structured programming and function definition "suggestions collection"
Shell编程规范与变量
Html+css+php+mysql realize registration + login + change password (with complete code)
seleniumwire获取百度指数
Relying on cloud business to support revenue growth alone, is Microsoft still overvalued?
Dynamic programming problem (6)
直流无刷电机控制器(换电机霍尔收费多少)
刷题的第三十天
Recursion / backtracking (middle)






