当前位置:网站首页>Advanced multithreading: Lock strategy
Advanced multithreading: Lock strategy
2022-07-28 05:35:00 【A salted fish..】
List of articles
Tips : The following is the main body of this article ,Java The series of learning will be continuously updated
1. Exclusive and shared locks
Shared lock :Share Lock (S lock ), ‘ read ’ Operations are not mutually exclusive ,‘ Write ’ Operations are mutually exclusive ,‘ read + Write ’ Operations are mutually exclusive .
An exclusive lock :exclusive Lock (X lock ), All operations are mutually exclusive .
If in a certain scene “ Read more than a writing ”, The efficiency of using read-write lock is very high .
Because only read data , Multiple threads read a data at the same time , It will not cause thread insecurity . Only modifying the same data will make the thread unsafe
Java Read write lock in :
ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
Lock readLock = readWriteLock.readLock();
Lock writeLock = readWriteLock.writeLock();
// readLock They are not mutually exclusive ,readLock and writeLock They are mutually exclusive ,writeLock They are mutually exclusive
readLock.lock(); // The main thread is added to the read lock
Thread t = new Thread() {
@Override
public void run() {
readLock.lock(); // The main thread has grabbed the read lock , The sub thread can still grab the lock
//writeLock.lock(); // Writing a lock is not enough
System.out.println(" A child thread can also successfully apply a read lock ");
}
};
t.start();
2. Reentrant locks and non reentrant locks
Reentrant lock : A thread already holds lock1 In case of lock , Allow to get lock1 The same lock .
synchronized、ReentrantLockAre reentrant locks .
public static void main(String[] args) {
Object lock = new Object();
synchronized (lock) {
// main The thread is already on lock Locked
synchronized (lock) {
// main Thread again on lock Request lock ( In the locked state )
System.out.println(" If you print it here, it means sync A lock is a relocatable lock ");
}
}
}
3. Fair and non-fair locks
Fair lock : Multiple threads acquire locks in the order in which they apply for locks , That is to say , If a thread group , It can ensure that every thread can get the lock .
for example :ReentrantLockYou can pass infair = true / falseTo control whether it is fair , The default is unfair .(fair = true, Synchronization queue used FIFO)
Not fair lock : The way to acquire locks is random , There is no guarantee that every thread can get the lock , Some threads will starve , I can't get the lock , for example :synchronized
summary : The performance of non fair lock is higher than that of fair lock , More reusable CPU Time for
4. Optimistic lock and pessimistic lock
The lock is not in the real sense , But in the case of multithreading , Evaluate concurrency to design locks :
Optimism lock : When multiple threads get the same shared resource , Optimistic that they will not modify the data , So don't lock it . Or only a few threads modify the data , You can use lightweight locking for concurrency control .cas It's the optimistic lock , Data synchronization is ensured by atomicity.
Pessimistic locking : Whether or not multiple threads frequently modify the same shared resource , Mutual exclusion must be used ( lock lock) For concurrency control . Such assynchronized、ReentrantLock
summary : Pessimistic lock is suitable for scenarios with many write operations , Optimistic lock is suitable for scenarios with more reading operations , The throughput of optimistic locks will be higher than that of pessimistic locks
What is? CAS?
CAS: Full name Compare and swap, Literally :”
Compare and exchange“, One CAS The following operations are involved :
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
principle : Go back and forth ( operation + Judge : actual value == Expected value ? End of cycle : Continue to operate + Judge )
CAS Application :
1. Realization java.util.concurrent.atomic The atomic class under the package
AtomicInteger atomicInteger = new AtomicInteger(0);
// amount to i++
atomicInteger.getAndIncrement();
2. Spin lock is realized
5. Mutexes and spinlocks
In terms of implementation principles :
Mutex( The mutex ) Belong to
sleep-waitingType of lock . For example, there are two threads on a single core machine ( Threads A And thread B). Assuming that thread A Want to get a critical area lock , At this point, the lock is being locked by the thread B Held by , So thread A Will be blocked , At this point, the thread A In the waiting queue , Wait for thread B Release the lock to wake up the thread A.
and Spin lock( spinlocks ) Applicable to multi-core computers , It belongs tobusy-waitingType of lock , If the thread A Lock not requested , Will not cause thread scheduling ( Give up CPU), Instead, it keeps cycling there to see if the owner of the spin lock has released the lock , Keep making lock requests , Until I get this lock .
The use of spinlocks :
① We should use spin lock carefully , Spin lock only in The kernel can be preemptive or SMP( Multicore ) We really need to , In the single CPU And under the non preemptive kernel , Spin lock operation is null operation .
②“ spinlocks ” The role of is In order to solve the mutually exclusive use of a resource . Because spin locks don't cause the caller to sleep ( Thread scheduling ), So spin lock is much more efficient than mutex .
③ The spin lock has been occupying CPU, He didn't get the lock , Has been running ( The spin ), So it takes up CPU, If you can't get the lock in a short time , This will undoubtedly make CPU Low efficiency . therefore Spin lock is more suitable for the case that the lock holder holds the lock for a relatively short time .
④ Trying to get a spin lock recursively is bound to cause a deadlock : The holding instance of the recursive program is in the second instance loop , To try to get the same spin lock , This spin lock will not be released .
summary :
Tips : Here is a summary of the article :
The above is today's learning content , This article is about Java Multithreaded learning , Recognize different locking strategies , And the application scenarios of these strategies . After that, the learning content will be continuously updated !!!
边栏推荐
- Tomato timing dimming table lamp touch chip-dlt8t10s-jericho
- 接口幂等性问题
- Mysql数据库索引(innodb引擎)
- C language: some self realization of string functions
- ByteBuffer.position 抛出异常 IllegalArgumentException
- MySQL date and time function, varchar and date are mutually converted
- Eccv2022 | 29 papers of Tencent Youtu were selected, including face security, image segmentation, target detection and other research directions
- First acquaintance with C language (2)
- 测试开发---自动化测试中的UI测试
- 解决Oracle使用in语句不能超过1000问题
猜你喜欢

Scope, execution process and life cycle of bean

BigDecimal rounds and retains two decimal places

Thesis writing function words

多线程进阶:volatile的作用以及实现原理

测试开发---自动化测试中的UI测试

个人写的一个文件上传工具网站

Multi module packaging: package: XXX does not exist

蒙特卡罗方法求解圆周率π并用turtle画点,以及完成进度条问题

【idea插件神器】教你如何使用IDEA一键set实体类中所有属性

Flask Development & get/post request
随机推荐
openjudge:找出全部子串位置
2021csdn blog star selection, mutual investment
Problems encountered when the registry service Eureka switches to nocas
2022 summer practice (PowerDesigner tutorial learning record) (first week)
First acquaintance with C language (2)
[slam] lvi-sam analysis - Overview
【单例模式】懒汉模式的线程安全问题
FusionGAN代码学习(一)
Digital twin technology creates visual application of smart mine
21 day SQL punch in summary
About localdatetime in swagger
What are the methods of array objects in Es5 and what are the new methods in ES6
项目中问题合集
Example of main diagram of paper model
个人写的一个文件上传工具网站
After ruoyi generates the code corresponding to the database, what should I do to make the following image look like
mysql 为查询结果增加序号
正则表达式
多线程进阶:volatile的作用以及实现原理
论文写作用词