当前位置:网站首页>[multithreading] lock strategy
[multithreading] lock strategy
2022-07-01 20:01:00 【Fly upward】
Catalog
1. Optimistic lock and pessimistic lock
2. Read / write locks and ordinary mutex locks
3. Heavyweight locks and lightweight locks
4. Hang wait lock and spin lock
5. Reentrant lock and Do not reenter the lock
7.3 CAS Implement atomic classes
8.2 Relevant interview questions
1. Optimistic lock and pessimistic lock
1) Optimism lock , That is, the probability of expected lock collision is very low .
Always assume the worst , Every time I go to get the data, I think others will modify it , So every time I get the data, I lock it , So people who want to take this data will block it until it gets the lock
for example , Even if the next epidemic comes , And don't worry about it , Life can work normally , A lot of food and supplies can be bought , No special preparation is required .( Optimism lock )
2) Pessimistic locking , That is, the probability of expected lock conflicts is very high
2. Read / write locks and ordinary mutex locks
1) For ordinary mutexes , There are only two operations : Lock and unlock
Two threads lock the same object , There will be mutual exclusion
Add read lock : If the code just reads , Just add a read lockAdd write lock : If a modification is made in the code , Just add a write lockUnlock
Between threads , There is no thread safety problem between data readers , But the writers of the data need to communicate with each other and with the readers To be mutually exclusive . If the same lock is used in both scenarios , There will be great performance loss . Therefore, read-write locks are generated .
ReentrantReadWriteLock.ReadLock Class represents a read lock . This object provides lock / unlock Method to lock and unlock .ReentrantReadWriteLock.WriteLock Class represents a write lock . This object also provides lock / unlock The method is to enter into Row lock unlock
Between read lock and read lock , There is no mutual exclusion ( Multiple threads read a variable at the same time , There will be no thread safety issues )
Between read lock and write lock , Between write lock and write lock , To be mutually exclusive
3. Heavyweight locks and lightweight locks
CPU Provides " Atomic operation instructions ".The operating system is based on CPU Atomic instructions for , Realized mutex The mutex .JVM Based on the mutex provided by the operating system , Realized synchronized and ReentrantLock Keywords and classes .
Be careful , synchronized Not just for mutex encapsulate , stay synchronized A lot of other work has been done internally
synchronized It starts with a lightweight lock . If the lock conflict is serious , Will become a heavyweight lock
2) Heavyweight lock
A large number of kernel mode user mode switchingIt's easy to trigger thread scheduling
3) Lightweight lock
A small number of kernel mode user mode switching .It is not easy to cause thread scheduling .
4) Understand user behavior vs Kernel mode
Imagine going to the bank to do business
4. Hang wait lock and spin lock
The pending lock is Heavyweight lock How to implement
advantage : Didn't give up CPU, Thread blocking and scheduling are not involved , Once the lock is released , You can get the lock at the first time .shortcoming : If the lock is held by other threads for a long time , Then it will continue to consume CPU resources . ( And the time to hang up waiting isDon't consume CPU Of
4. Fair lock and unfair lock
5. Reentrant lock and Do not reenter the lock
One thread , Lock the same lock for two consecutive times , If it will deadlock, it is a non reentrant lock , If it doesn't deadlock , It's a re-entry lock .synchronized It's a reentrant lock
6. synchronized Lock summary
1) Both an optimistic lock , It is also a pessimistic lock . ( Adaptive according to the intensity of lock competition )
2) It's not a read-write lock, it's just an ordinary mutex .
3) It's both a lightweight lock , It's also a heavyweight lock ( According to the intensity of lock competition , The adaptive )
4) The part of lightweight lock is based on spin lock . The heavyweight part is based on the pending lock
5) Not fair lock
6) Reentrant lock .
7. CAS
Let's assume that the raw data in memory V, Old expectations A, New values that need to be modified B.1. Compare A And V Whether it is equal or not .( Compare )2. If it's equal , take B write in V.( In exchange for )3. Whether the return operation is successful .
7.1 CAS Pseudo code
boolean CAS(address, expectValue, swapValue) {
if (&address == expectedValue) {
&address = swapValue;
return true;
}
return false;
}
CAS It can be regarded as an optimistic lock . ( Or it can be understood as CAS It's an implementation of optimistic lock )
7.2 CAS How did it happen
java Of CAS Take advantage of unsafe This class provides CAS operation ;unsafe Of CAS Rely on jvm For different operating systems Atomic::cmpxchg;Atomic::cmpxchg The implementation of using the assembly of CAS operation , And use cpu Hardware provided lock The mechanism guarantees its atomicity
7.3 CAS Implement atomic classes
public class Demo5 {
public static void main(String[] args) throws InterruptedException {
AtomicInteger num = new AtomicInteger(0);
Thread t1 = new Thread(() ->{
for (int i = 0; i < 5000; i++) {
// This method is equivalent to num++
num.getAndIncrement();
}
});
Thread t2 = new Thread(() ->{
for (int i = 0; i < 5000; i++) {
// This method is equivalent to num++
num.getAndIncrement();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(num.get());
}
}
There is no thread safety problem in the above code .
be based on CAS Realized ++ operation .
This can ensure thread safety , And can compare with synchronized Efficient .
synchronized Will involve lock competition , Two threads have to wait for each other .
CAS Thread blocking and waiting are not involved
7.4 Spin lock
public class SpinLock {
private Thread owner = null;
public void lock(){
// adopt CAS See if the current lock is held by a thread .
// If the lock is already held by another thread , Then wait .
// If the lock is not held by another thread , Then put owner Set to the thread currently trying to lock .
while(!CAS(this.owner, null, Thread.currentThread())){
}
}
public void unlock (){
this.owner = null;
}
}
Similar to the atomic class above , It is also realized through a loop .
Call... In the loop CAS.CAS Will compare current owner Is the value null,
If it is null Change to the current thread . It means that the current thread has got the lock .
If not null Just go back to false, Into the next loop .
The next cycle is still going on CAS operation
If the current lock is one Directly held by others , The thread currently trying to lock will be in this while Where fast
Repeat the cycle ~~~ => The spin ~~ ( Busy etc. )
Spin lock is a lightweight lock, which can also be regarded as an optimistic lock .
8. CAS Of ABA problem
hypothesis A Yes 100 deposit .,A Want to ATM take 50 Yuan . The ATM creates two threads , Execute concurrently -50 operation .We expect a thread to execute -50 success , Another thread -50 Failure .( Another thread is stuck when the machine breaks down , Press one more withdrawal , The thread is enabled , Failed to use to withdraw )
1) deposit 100. Threads 1 The current deposit value obtained is 100, Expect to update to 50; Threads 2 The current deposit value obtained is 100, Expect to update to 50.2) Threads 1 Deduction successfully executed , The deposit was changed to 50. Threads 2 Blocking waiting .3) It's the thread's turn 2 Yes , It is found that the current deposit is 50, And what I read before 100 inequality , Execution failure .Finally take it out 50
Abnormal process :
1) deposit 100. Threads 1 The current deposit value obtained is 100, Expect to update to 50; Threads 2 The current deposit value obtained is 100, Expect to update to 50.2) Threads 1 Deduction successfully executed , The deposit was changed to 50. Threads 2 Blocking waiting .3) In a thread 2 Perform before , A My friend just gave me A Transfer accounts 50, The account balance becomes 1004) It's the thread's turn 2 Yes , It is found that the current deposit is 100, And what I read before 100 identical , Perform the deduction operation againFinally take it out 100
This is the time , The deduction operation was performed twice , Namely ABA Caused by the
8.1 Solution
Give the value to be modified , Introduce version number .. stay CAS Compare the current value of the data with the old value , Also compare whether the version number meets the expectation .
CAS The operation reads the old value while , Also read the version number .When it's really revised ,If the current version number is the same as the read version number , Then modify the data , And put the version number + 1.If the current version number is higher than the read version number . The operation failed ( Think the data has been modified ).
stay Java The standard library provides AtomicStampedReference<E> class . This class can wrap a class , In-house mention It provides the version management function described above .
8.2 Relevant interview questions
Full name Compare and swap, namely " Compare and exchange ". Equivalent to the operation of an atom , Simultaneous completion " Read memory , Comparison is equal , Modify memory " These three steps . Essentially, we need CPU Support of instructions .
2) ABA How to solve the problem ?
Introduce the version number to the data to be modified . stay CAS Compare the current value of the data with the old value , Also compare whether the version number meets the expectation .If the current version number is found to be consistent with the version number read before , Just really perform the modification operation , And let the version number increase ; If you find that the current version number is larger than the version number you read before , It is considered that the operation failed .
边栏推荐
猜你喜欢
为定时器和延时器等其它情况的回调函数绑定当前作用域的this
开发那些事儿:EasyCVR平台添加播放地址鉴权功能
实例讲解将Graph Explorer搬上JupyterLab
EURA欧瑞E1000系列变频器使用PID实现恒压供水功能的相关参数设置及接线
Bind this of the current scope for callback functions in other cases such as timers and delayers
Interview question 1
Interview questions shared in today's group
1592 example 1 King (sgu223 loj10170 luogu1896 increase + / provincial election -) violent thinking pressure DP 01 Backpack
A quietly rising domestic software, low-key and powerful!
ModSim基本使用(Modbus模拟器)
随机推荐
Flask 常用组件
Procédure de mesure du capteur d'accord vibrant par le module d'acquisition d'accord vibrant
全国职业院校技能大赛网络安全“splunk“详细配置
[AI server setup] CUDA environment
STC 32位8051单片机开发实例教程 二 I/O工作模式及其配置
由浅入深学会白盒测试用例设计
How to add transactions in JDBC
简单但现代的服务器仪表板Dashdot
A quietly rising domestic software, low-key and powerful!
面试题篇一
上大学后明白了哪些坑人的事?
关于new Set( )还有哪些是你不知道的
Bind this of the current scope for callback functions in other cases such as timers and delayers
How to use console Log print text?
list大集合等比分割成多个小list集合
Using win7 vulnerability to crack the system login password
独家消息:阿里云悄然推出RPA云电脑,已与多家RPA厂商开放合作
STC 32-bit 8051 single chip microcomputer development example tutorial three program compilation setting and download
RichView TRVDocParameters 页面参数设置
C#聯合halcon應用——大華相機采集類