当前位置:网站首页>AQS learning
AQS learning
2022-04-23 20:05:00 【Fairy wants carry】
Catalog
Protection methods that need to be implemented by subclasses
Difference between lock and synchronizer
Custom Lock - An exclusive lock
summary :
Inherit it to realize the function of the parent class
Get the lock :
Blocking and obtaining resources is park and unpark;
Release the lock :
Determine whether there are lock resources :
AbstractQueuedSynchronizer Public methods (AQS)
1.acquire: Get sync state exclusively ;
2.release: Exclusive release synchronization state ;
3.acquireShared(int arg):
Shared get synchronization status , If the current thread does not get the synchronization state , Then go into the queue and wait ——> The main difference from exclusive mode is that multiple threads can obtain synchronization status at the same time ;
4.releaseShared(int arg): Shared release synchronization state ;
Protection methods that need to be implemented by subclasses
1.tryAcquire: Get sync state exclusively ;—— adopt cas Operate to set the lock resource occupancy status , And for the lock Owner Set it up
2.tryRelease: Exclusive release synchronization state ;
3.getState: Return to lock state
There are several more. shared
Other methods
Difference between lock and synchronizer
lock : For users , Defines how locks interact with users , Hidden the details ;
synchronizer : For lock implementers , Simplifies the implementation of locks ;
The lock and synchronizer well isolate the user from the areas that need to be concerned by the implementation ;
Custom Lock - An exclusive lock
package com.example.juc.AQS;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import static java.lang.Thread.sleep;
/**
* @author diao 2022/4/23
*/
@Slf4j(topic = "c.TestAqs")
public class TestAqs {
public static void main(String[] args) {
MyLock lock = new MyLock();
new Thread(()->{
lock.lock();
log.debug("locking...");
lock.lock();//synchronized and ReentrantLock Are reentrant
try {
log.debug("locking...");
sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
log.debug("unlocking...");
lock.unlock();
}
},"t1").start();
// new Thread(()->{
// lock.lock();
// try {
// log.debug("locking...");
// } finally {
// log.debug("unlocking...");
// lock.unlock();
// }
// },"t2").start();
}
}
// Custom Lock ( Do not reenter the lock ); Reentrant lock : You can enter the lock resource the next time you enter
class MyLock implements Lock{
// An exclusive lock ,AQS Based on queues ( synchronizer )
class MySync extends AbstractQueuedSynchronizer{
/*1. Try to get lock resources */
@Override
protected boolean tryAcquire(int arg) {
// Because there may be multiple threads competing for lock resources , So go ahead with cas
if(compareAndSetState(0,1)){
// Try to lock the owner Set as current thread
setExclusiveOwnerThread(Thread.currentThread());
return true;
}
return false;
}
/*2. Try to release the lock resource */
@Override
protected boolean tryRelease(int arg) {
// Here we need to pay attention to the order ,setState Yes volatile Field
// There is a read-write barrier , The previous modification lock has resources that are visible to other threads
setExclusiveOwnerThread(null);
setState(0);
return true;
}
/*3. Determine whether to hold an exclusive lock */
@Override
protected boolean isHeldExclusively() {
return getState()==1;
}
public Condition newCondition(){
return new ConditionObject();
}
}
private MySync sync=new MySync();
@Override// Lock ( You don't succeed , Will enter the waiting queue )
public void lock() {
sync.acquire(1);
}
@Override// Lock , Can interrupt
public void lockInterruptibly() throws InterruptedException {
sync.acquireInterruptibly(1);
}
@Override
public boolean tryLock() {
return sync.tryAcquire(1);
}
@Override// Try to lock , With timeout
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return sync.tryAcquireNanos(1,unit.toNanos(time));
}
@Override// Unlock
public void unlock() {
/**
* and sync Medium tryRelease It's different
* The above is just to change the owner of the lock and the of the lock state, Threads are not blocked but will not wake up
* release Wakes up blocked threads
*/
sync.release(1);
}
@Override// Returns the condition variable
public Condition newCondition() {
return sync.newCondition();
}
}
As the code shows , Exclusive lock realizes that only one thread can obtain the lock at the same time , Other threads that acquire locks can only wait in the waiting queue ;
AQS Summary
Usage mode ?
AQS Mainly through inheritance , Subclasses inherit the synchronizer and implement its abstract methods -> To manage synchronization status ;
How to manage synchronization status ?
AQS Use one int A member variable of type state To indicate the synchronization state , When state>0 Indicates that the lock has been acquired , When state = 0 When the lock is released . It offers three ways (getState()、setState(int newState)、compareAndSetState(int expect,int update)) To synchronize state state To operate , Of course AQS Make sure you are right state The operation of is safe .
characteristic :
AQS adopt Built in FIFO Synchronize the queue to complete the queuing of resource acquisition thread , If the current thread fails to get the synchronization status ,AQS The current thread and wait status will be constructed into a node (Node) And add it to the synchronization queue , At the same time, it will block the current thread ;
Stand at the angle of use , I understand that there are only two functions : Exclusive and shared , Either exclusive or shared , Then call the bottom api;
AQS The general realization of
AQS One was maintained internally CLH Queue to manage locks . The thread will first try to acquire the lock , If it fails, it will wrap the current thread and wait status information into a node Nodes join the synchronization queue sync queue in . And then it's going to loop around trying to get the lock ( The spin ), The condition is that the current node is head The immediate successor will try . If you fail, you will block yourself until you are awakened . When the thread holding the lock releases the lock , Will wake up subsequent threads in the queue .
CLH(Craig,Landin,and Hagersten) 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 .
版权声明
本文为[Fairy wants carry]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231947061595.html
边栏推荐
- 深度学习——特征工程小总结
- 音频编辑生成软件
- Deep learning -- Summary of Feature Engineering
- Mysql database - single table query (I)
- Redis core technology and practice 1 - start with building a simple key value database simplekv
- MySQL advanced lock - overview of MySQL locks and classification of MySQL locks: global lock (data backup), table level lock (table shared read lock, table exclusive write lock, metadata lock and inte
- 【文本分类案例】(4) RNN、LSTM 电影评价倾向分类,附TensorFlow完整代码
- Video understanding
- MySQL 进阶 锁 -- MySQL锁概述、MySQL锁的分类:全局锁(数据备份)、表级锁(表共享读锁、表独占写锁、元数据锁、意向锁)、行级锁(行锁、间隙锁、临键锁)
- Grafana 分享带可变参数的链接
猜你喜欢
Fundamentals of programming language (2)
Kubernetes入门到精通-KtConnect(全称Kubernetes Toolkit Connect)是一款基于Kubernetes环境用于提高本地测试联调效率的小工具。
Openharmony open source developer growth plan, looking for new open source forces that change the world!
C6748 software simulation and hardware test - with detailed FFT hardware measurement time
Decompile and get the source code of any wechat applet - just read this (latest)
SIGIR'22「微软」CTR估计:利用上下文信息促进特征表征学习
Unity创建超写实三维场景的一般步骤
ESP8266-入门第一篇
Project training of Software College of Shandong University - Innovation Training - network security shooting range experimental platform (6)
[报告] Microsoft :Application of deep learning methods in speech enhancement
随机推荐
MySQL数据库 - 数据库和表的基本操作(二)
MySQL syntax collation (5) -- functions, stored procedures and triggers
How to select the third-party package of golang
R语言使用caret包的preProcess函数进行数据预处理:对所有的数据列进行BoxCox变换处理(将非正态分布数据列转换为正态分布数据、不可以处理负数)、设置method参数为BoxCox
MySQL数据库 - 连接查询
MFC obtains local IP (used more in network communication)
[H264] hevc H264 parsing and frame rate setting of the old version of libvlc
The textarea cursor cannot be controlled by the keyboard due to antd dropdown + modal + textarea
Redis core technology and practice 1 - start with building a simple key value database simplekv
Kubernetes introduction to mastery - ktconnect (full name: kubernetes toolkit connect) is a small tool based on kubernetes environment to improve the efficiency of local test joint debugging.
Mysql database - single table query (III)
@Mapperscan and @ mapper
Fundamentals of programming language (2)
Grafana shares links with variable parameters
Use test of FFT and IFFT library functions of TI DSP
MySQL数据库 - 单表查询(一)
NiO related Basics
Introduction to electron tutorial 3 - process communication
Electron入门教程4 —— 切换应用的主题
MySQL syntax collation (2)