当前位置:网站首页>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

边栏推荐
- Jupyter notebook中5个有趣的魔法命令
- Solutions such as failed plug-in installation and slow speed of linking remote server under vscode
- 【无标题】
- Alibaba code index technology practice: provide reading experience of local IDE for code review
- flask与七牛云上传图片
- 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)
- 17. Design of machine learning system
- Send SMS verification code asynchronously using Ronglian cloud celery
- 最长上升子序列
- IMG tags prohibit dragging pictures
猜你喜欢

There is a span tag. If you want to do click events on it, how can you expand the click area

PTA (one question per day) 7-76 ratio

zabbix部署及监控

17.机器学习系统的设计

【愚公系列】2022年07月 Go教学课程 020-Go容器之数组

PTA (daily question) 7-77 encryption

Cause analysis of 12 MySQL slow queries

How to solve the problems of MQ message loss, duplication and backlog?

手把手教你安装Latex(保姆级教程)

时间序列数据的预处理方法总结
随机推荐
Alibaba Code代码索引技术实践:为Code Review提供本地IDE的阅读体验
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)
Depth first search (DFS) and its matlab code
SDRAM控制器设计(数字控制器的两种设计方法)
IMG tags prohibit dragging pictures
[development tutorial 11] crazy shell · open source Bluetooth heart rate waterproof sports Bracelet - explanation of the function code of the whole machine
Calculate properties and listeners
Flask sends verification code in combination with Ronglian cloud
rk3399 9.0驱动添加Powser按键
将Word中的表格以图片形式复制到微信发送
时间序列数据的预处理方法总结
Anti shake and throttling
ORACLE not available如何解决
SAP vl02n delivery note posting function WS_ DELIVERY_ UPDATE
Execute immediate simple sample set (DML)
Android必备的面试技能(含面试题和学习资料)
多线程顺序运行的几种方法,面试可以随便问
“吃货联盟定餐系统”
Longest ascending subsequence
JWT token related configuration (global configuration identity authentication rewrites authenticate method)






