当前位置:网站首页>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个有趣的魔法命令
- 靠云业务独撑收入增长大梁,微软仍然被高估?
- 异步模式之工作线程
- Tips for API interface optimization
- Xinchi technology released the latest flagship product of G9 series, equipped with six A55 cores with 1.8GHz dominant frequency
- 15. Model evaluation and selection
- Relying on cloud business to support revenue growth alone, is Microsoft still overvalued?
- C语言括号匹配(栈括号匹配c语言)
- Flash and seven cattle cloud upload pictures
- 直流无刷电机控制器(换电机霍尔收费多少)
猜你喜欢

追踪伦敦银实时行情的方法

我不建议你使用SELECT *

Xinchi technology released the latest flagship product of G9 series, equipped with six A55 cores with 1.8GHz dominant frequency

Alibaba Code代码索引技术实践:为Code Review提供本地IDE的阅读体验

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

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

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)

NPM run serve stuck at 40%

17.机器学习系统的设计

AQS原理
随机推荐
IMG tags prohibit dragging pictures
Andriod6.0 low power mode (turn off WiFi, Bluetooth, GPS, screen brightness, etc.)
Breadth first search (BFS) and its matlab code
What are the skills of API interface optimization?
17.机器学习系统的设计
将行内元素转换为块元素的方法
Error reporting: when the browser clicks the modify add button, there is no response and no error reporting. Solution
我不建议你使用SELECT *
Send SMS verification code asynchronously using Ronglian cloud celery
How to solve Oracle not available
Flask sends verification code in combination with Ronglian cloud
PTA (one question per day) 7-76 ratio
Basic knowledge of PHP language (super detailed)
Depth first search (DFS) and its matlab code
SAP vl02n delivery note posting function WS_ DELIVERY_ UPDATE
15.模型评估和选择问题
Flyway's quick start tutorial
MATLAB02:结构化编程和函数定义「建议收藏」
DRF -- authentication, authority, frequency source code analysis, global exception handling, automatic generation of interface documents, RBAC introduction
Requestvideoframecallback() simple instance






