当前位置:网站首页>Research on the implementation principle of reentrantlock in concurrent programming learning notes
Research on the implementation principle of reentrantlock in concurrent programming learning notes
2022-07-29 05:57:00 【People with different feelings】
1、 Preface
We have learned before that Lock Interface , It is a basic definition of lock operation method , It provides synchronized Keyword has all the functions and methods , and ReentrantLock Class not only fully implements the display lock Lock Interface defined by interface , It also extends the use of explicit locks for Lock Some monitoring methods . meanwhile , We also try to use ReentrantLock Realize synchronous access to shared resources , In this section, let's have a deep understanding , How to realize these functions .
2、ReentrantLock( Reentrant lock ) Realization principle
2.1、ReentrantLock Implementation of interface methods
By looking at ReentrantLock Class source code , We will find all the implementations Lock Interface method , Including some additional monitoring methods , In fact, they all rely on one Sync variable-implemented , As shown below :
public void lock() {
sync.lock();
}
public void lockInterruptibly() throws InterruptedException {
sync.acquireInterruptibly(1);
}
public boolean tryLock() {
return sync.nonfairTryAcquire(1);
}
public void unlock() {
sync.release(1);
}
public Condition newCondition() {
return sync.newCondition();
}
//ReentrantLock Some monitoring methods implemented , Also with the help of sync Realized , The code is as follows ( The space for , Only one description is shown )
public int getHoldCount() {
return sync.getHoldCount();
}
//……
Through the above part of the source code , We can already confirm ReentrantLock The realization of the class , Based mainly on sync object , As long as we put Sync The object study is clear , that ReentrantLock We naturally understand the principle of class , Let's start to learn Sync The realization of the class .
2.2、ReentrantLock Constructors
ReentrantLock It provides the mechanism of fair lock and unfair lock , Based mainly on Sync Implementation class of FairSync and NonfairSync Realization . The default constructor uses a mechanism of unfair locking , You can use constructors with parameters , Apply fair lock mechanism . The constructor is as follows :
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}
public ReentrantLock() {
sync = new NonfairSync();
}
2.2、Sync Inner class
ReentrantLock Yes Lock The realization of is based on Sync To do the , In the previous source code has been clearly seen , Here we will focus on learning Sync The realization of the class .
Sync The hierarchy of classes :
according to Sync Hierarchical structure , We can know that this class inherits AbstractQueuedSynchronizer(AQS) abstract class , There are two implementation classes at the same time FairSync and NonfairSync, It is applied to fair lock and unfair lock mechanisms respectively . among ,AbstractQueuedSynchronizer Abstract classes define a set of synchronization templates for multithreading to access shared resources , Solved a lot of detail problems when implementing synchronizer , Can greatly reduce the implementation work , namely AbstractQueuedSynchronizer Provides a unified template function for locking and unlocking process ,Sync Class only needs to implement some abstract methods .
There is no in-depth study here for the time being AbstractQueuedSynchronizer(AQS) abstract class , The following is a special introduction .
stay Sync Class , Mainly achieved nonfairTryAcquire() and tryRelease() Method , Of course , There are other ways to implement , Please see the notes of the source code for details :
abstract static class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = -5179523762034025860L;
/** * Abstract method , In the implementation class FairSync and NonfairSync To realize , * In the methods of implementing classes , Determines the fair lock or unfair lock strategy for obtaining locks */
abstract void lock();
/** * Not fair lock - Try to get the lock resource , The method that the fair lock attempts to obtain resources is implementing classes FairSync To realize . */
final boolean nonfairTryAcquire(int acquires) {
// Get the current thread
final Thread current = Thread.currentThread();
// obtain state state , Indicates the lock status ,getState() Method in AbstractQueuedSynchronizer(AQS) Implement... In abstract classes .
int c = getState();
if (c == 0) {
// be equal to 0, Indicates that the resource is available
//cas Method to set state , Guaranteed atomicity
if (compareAndSetState(0, acquires)) {
// To be successful , Set the thread holding the lock , And return to acquire the lock successfully
setExclusiveOwnerThread(current);
return true;
}
}else if (current == getExclusiveOwnerThread()) {
// Determine whether the current thread holds a lock , Reentrant property
// Set up state The numerical
int nextc = c + acquires;
if (nextc < 0) // When it exceeds the limit
throw new Error("Maximum lock count exceeded");
// Current thread settings , Unwanted cas The way
setState(nextc);
return true;
}
return false;
}
/** * Release lock resource */
protected final boolean tryRelease(int releases) {
// Calculate if the release is successful , The current thread holds hold Number
int c = getState() - releases;
// Determine whether the current thread releases the lock , No. , Throw an exception
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
// If c==0, Indicates that the lock is released successfully , At the same time, set the thread holding the lock to null
if (c == 0) {
free = true;
setExclusiveOwnerThread(null);
}
//c==0 when ,free=true, Lock release successful ,c!=0 when ,free=false, Failed to release lock , It indicates that there is a reentry operation
setState(c);
return free;
}
/** * Whether the current thread holds a lock */
protected final boolean isHeldExclusively() {
return getExclusiveOwnerThread() == Thread.currentThread();
}
/** * establish Condition object */
final ConditionObject newCondition() {
return new ConditionObject();
}
/** * Get the thread holding the lock */
final Thread getOwner() {
return getState() == 0 ? null : getExclusiveOwnerThread();
}
/** * obtain Hold Number , It is the current thread that holds the lock , Just go back to state, otherwise ( When the current thread does not hold a lock ), return 0 */
final int getHoldCount() {
return isHeldExclusively() ? getState() : 0;
}
/** * Whether lock resources are occupied */
final boolean isLocked() {
return getState() != 0;
}
/** * Deserialization */
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
setState(0); // reset to unlocked state
}
}
2.3、NonfairSync Implementation class ( Unfair lock strategy )
Thread that failed to get lock , Will enter CLH Queue blocking , Other threads will wake up when they are unlocked CLH Queue thread , When re competing for locks , If not CLH The thread of the queue ( I haven't had time to enter CLH Queue blocked threads ) Take part in the competition , Then it is the unfair lock strategy .
Implementation class of unfair lock policy NonfairSync , Mainly achieved Sync Class lock(), In this method , Implements the unfair lock strategy ; It also realizes tryAcquire() Method ( The main logic is Sync Class nonfairTryAcquire() Method implementation ), Used to get , As follows :
static final class NonfairSync extends Sync {
private static final long serialVersionUID = 7316153563782823691L;
/** * Get lock resources , I feel that if lock competition occurs , There happens to be a thread to get the lock , Will it be better than CLH Blocking threads in the queue is easier to obtain locks ? */
final void lock() {
if (compareAndSetState(0, 1))//cas Method attempts to set , If the setting is successful , The current thread can acquire the lock
setExclusiveOwnerThread(Thread.currentThread());
else
// stay AbstractQueuedSynchronizer(AQS) Implement... In abstract classes , perform AQS The process of obtaining lock
acquire(1);
}
/** * Try to get lock resources , stay Syns Definition in class nonfairTryAcquire() Method */
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
}
2.4、FairSync Implementation class ( Fair lock strategy )
FairSync Process and NonfairSync similar , It's all implemented lock() and tryAcquire() Method , The difference lies in :
- lock() Method implementation , stay FairSync Called directly in acquire(1) Method , And in the NonfairSync Class , First of all cas operation , Then it was called after failure acquire(1) Method .
- stay tryAcquire() In the method ,FairSync Class implements logic inside itself , And in cas Before operation , More than a step hasQueuedPredecessors function , Verify that it is CLH Blocking queues , and NonfairSync Class , It calls nonfairTryAcquire() Method , And there is no need to verify whether it is CLH Blocking queues .
static final class FairSync extends Sync {
private static final long serialVersionUID = -3000897897090466540L;
final void lock() {
// Call directly AbstractQueuedSynchronizer(AQS) In an abstract class acquire(), perform AQS The process of obtaining lock
acquire(1);
}
/** * Get lock resources */
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
//hasQueuedPredecessors() Method in AQS Defined in abstract class , Verify whether the current site is CLH Blocking the queue , Not in line , Failed to acquire lock , You also need cas Operational verification .
if (!hasQueuedPredecessors() &&
compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;
if (nextc < 0)
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
}
3、 summary
thus , About ReentrantLock We will finish learning the implementation principle of , But it involves CLH Blocking queues 、AQS In an abstract class hasQueuedPredecessors()、acquire() Other methods , We didn't study deeply , We plan to do it in the next section , Make a special in-depth study AQS Implementation principle of , Coming soon !!!
边栏推荐
- CMD window under Windows connects to MySQL and operates the table
- Okaleido tiger logged into binance NFT on July 27, and has achieved good results in the first round
- 微信小程序源码获取(附工具的下载)
- Machine learning makes character recognition easier: kotlin+mvvm+ Huawei ml Kit
- Markdown语法
- My ideal job, the absolute freedom of coder farmers is the most important - the pursuit of entrepreneurship in the future
- Basic use of array -- traverse the circular array to find the maximum value, minimum value, maximum subscript and minimum subscript of the array
- XDFS&空天院HPC集群典型案例
- Super simple integration of HMS ml kit to realize parent control
- 初探fastJson的AutoType
猜你喜欢
Crypto giants all in metauniverse, and platofarm may break through
How can Plato obtain premium income through elephant swap in a bear market?
Laravel service container (inheritance and events)
Training log III of "Shandong University mobile Internet development technology teaching website construction" project
yum本地源制作
与张小姐的春夏秋冬(3)
ssm整合
mysql插入百万数据(使用函数和存储过程)
深度学习的趣味app简单优化(适合新手)
超简单集成HMS ML Kit 实现parental control
随机推荐
Super simple integration HMS ml kit face detection to achieve cute stickers
华为2020校招笔试编程题 看这篇就够了(上)
Idea using JDBC to connect mysql database personal detailed tutorial
数组的基础使用--遍历循环数组求出数组最大值,最小值以及最大值下标,最小值下标
Mobile terminal -flex item attribute
Detailed explanation of tool classes countdownlatch and cyclicbarrier of concurrent programming learning notes
Markdown语法
Novice introduction: download from PHP environment to thinkphp6 framework by hand
How does PHP generate QR code?
The Platonic metauniverse advocated by musk has long been verified by platofarm
一文读懂Move2Earn项目——MOVE
30 knowledge points that must be mastered in quantitative development [what is level-2 data]
『全闪实测』数据库加速解决方案
Use of xtrabackup
Detailed steps of JDBC connection to database
如何零代码制作深度学习的趣味app(适合新手)
Laravel swagger add access password
与张小姐的春夏秋冬(1)
Flink connector Oracle CDC 实时同步数据到MySQL(Oracle19c)
Process management of day02 operation