当前位置:网站首页>Thread lock and its ascending and descending levels
Thread lock and its ascending and descending levels
2022-07-29 01:07:00 【SnnnSn~】
Catalog
One 、Lock brief introduction 、 status 、 effect
1、 The classification of locks is shown in the figure :
2. Optimism lock Pessimistic locking
3、 Reentrant and non reentrant locks , With ReentrantLock For example ( a key )
5、 Shared lock and exclusive lock
One 、Lock brief introduction 、 status 、 effect
1、 A lock is a tool , Used to control access to shared resources ;
2、Lock and synchronized, These two are the most common locks , They can all achieve thread safety , But there are great differences in use and function ;
3、Locak Not to replace synchronized Of , But when using synchronized When it is inappropriate or insufficient to meet the requirements , To provide advanced functionality ;
4、Lock The most common implementation classes of interfaces are ReentrantLock;
5、 Usually ,Lock Only one thread is allowed to access this shared resource . But sometimes , Some special implementations allow concurrent access , such as ReadWriteLock Inside ReadLock;
6、 Why? synchronized Not enough use ?
- Low efficiency : Less lock release 、 Cannot set timeout when trying to acquire lock 、 Cannot interrupt a thread that is trying to acquire a lock ( When entering synchronized Thread in , If something unusual happens ,JVM Will let it release the lock );
- inflexible ( Read and write lock is more flexible ): Lock and release at a single time , Each lock has a single condition ( An object ), It may not be enough ;
- Can't know if the lock was successfully acquired .
Two 、Lock Method
1、locak()
- lock() Is the most common lock acquisition . If the lock is acquired by another thread , Then wait ;
- Lock Don't like synchronized The lock is automatically released in case of exception ;
- So the best practice is , stay finally Middle release lock , To ensure that the lock will be released when an exception occurs ;
2、tryLock()
- tryLock() To attempt to acquire a lock , If the current lock is not occupied by another thread , To achieve success , And back to true, Otherwise return to false;
- This method immediately returns , Don't like lock() equally , If you can't get the lock, it's blocked there ;
- tryLock(long time , TimeUnit unit): If the lock has not been obtained within the timeout , return false, If you can get the lock , Just get the lock , And back to true.
3、lockInterruptibly()
- lockInterruptibly() amount to tryLock(long time , TimeUnit unit) Set the timeout to infinite . While waiting for the lock , Threads can be interrupted .
4、unlock(): Unlock
5、interrupt() Method :
- Its function is to interrupt this thread , It can be interrupted lockInterruptibly() Get the lock , And running thread , You can also interrupt the use lockInterruptibly() The thread waiting to acquire the lock . however interrupt() Do not interrupt the use lock() The thread waiting to acquire the lock , Also cannot interrupt the use lock() Get the lock , And running thread , Unless , This thread runs to Thread.sleep(), He throws an exception , And perform finally Medium unlock() Release the lock .
6、interrupted() Method :
- The function is to test whether the current thread is interrupted ( Check interrupt flag ), Return to one boolean And clear the interrupt state , The interrupt state has been cleared on the second call , Will return a false.
7、isInterrupted() Method :
- The function is to test whether this thread is interrupted , Do not clear the interrupt state .
3、 ... and 、 lock
1、 The classification of locks is shown in the figure :
2. Optimism lock Pessimistic locking
2.1 What is optimistic lock
I think I won't be disturbed by other threads when processing operations 1, Therefore, the operated object will not be locked
When updating , To compare whether the data during the period when I modified the data has been modified by others , If Has not been changed , It means that we are really the only ones operating , Go to modify the data normally .
If the data is different from what you got at the beginning , explain Others modified the data , You cannot use the data just updated , give up 、 Strategies such as error reporting and retry .
Optimistic lock is generally used CAS Algorithm implementation .
The typical optimistic lock is atomic class , Concurrent container .
2.2 Pessimistic locking
- If I don't lock this resource , Others will come and fight , Will cause data result error , So every time, in order to ensure the correctness of the results , Every time you get and modify data , Lock the data , Make the data inaccessible to others , This ensures that the data content is safe ;
- Java The implementation of pessimistic lock in is synchronized and Lock Related classes .
2.3 Two kinds of lock use scenarios
1. Pessimistic locking : It is suitable for multiple concurrent writes , It is used in the case that the critical area takes a long time to lock , Pessimistic lock can avoid a lot of useless spin consumption .
Typical case :
- The critical area has IO operation .
- The critical area code is complex , Large circulation
- The critical area is highly competitive
2. Optimism lock , Suitable for less concurrent writes , Most of them are read scenes , Unlocked can greatly improve the reading performance .
3、 Reentrant and non reentrant locks , With ReentrantLock For example ( a key )
1) Reentrant lock
When the same thread does not release the lock , Repeatedly obtain the lock you hold .
2) Non reentrant lock
1、 A non reentrant lock is a direct attempt to acquire a lock , If the lock is already held , Can't get the lock again ;
2、 When releasing the lock, it will also directly status Set as 0.
3) The difference between reentrant lock and non reentrant lock :
1、 Reentrant locks are generally a class with AB Two methods , and A and B There is a unified lock , When implemented A Method, you can get the lock , But in A It can also be used directly when all the methods have not been released B Method , At this time, you can also get this lock .
2、 Non reentrant lock also refers to A and B Two methods ,A and B You can get a unified lock , And in the A There is no way to use the method before it is released B Methodical , That is to say, we have to wait A It can only be used after release B Method .
4、 Fair and non-fair locks
1) A fair situation ( With ReentrantLock For example )
1、 establish ReentrantLock Time passes in true Parameters can be ;
2、 In a thread 1 perform unlock() After releasing the lock , Because at this point the thread 2 The longest waiting time , So threads 2 Get executed first , Then there are threads 3、 Threads 4.
2) Unfair situation ( With ReentrantLock For example )
1、 establish ReentrantLock Time passes in false Parameters can be passed or not ;
2、 If in thread 1 When you release the lock , Threads 5 Just to execute lock(), Just cut in line ;
3、 Threads 5 You can jump in line , Just get this lock , It's also ReentrantLock Default fairness policy , That is to say “ Unfair ”
advantage | Inferiority | |
Fair lock | All threads are fair and equal , Each thread waits for a period of time , There is always an opportunity to implement | More slowly , Smaller throughput |
Unfair lock | faster , Large throughput | There is a possibility of thread starvation , That is, some threads cannot execute for a long time . |
5、 Shared lock and exclusive lock
1、 What are shared locks and exclusive locks
1) Shared lock
- Shared lock , Also known as read lock , After getting the shared lock , Can view but not modify and delete data , Other threads can also obtain the shared lock at this time , You can also view but cannot modify or delete data .
2) Exclusive lock
- Exclusive lock , Also known as exclusive lock 、 Exclusive lock .
3) Shared locks and exclusive locks are typically read-write locks ReentrantReadWriteLock, The read lock is a shared lock , Write lock is exclusive lock .
2、 The function of read-write lock
1) Before there is no read-write lock , Let's suppose we use ReentrantLock, So although we guarantee thread safety , But it also wastes some resources : Multiple read operations are performed simultaneously , No thread safety issues ;
2) Use a read lock where you read , Use a write lock where you write , Flexible control , If there is no write lock , Reading is non blocking , Improve the efficiency of the program .
3、 Read write lock rules
1) Multiple threads only apply for read locks , Can apply to ;
2) If a thread has occupied a read lock , At this time, if other threads want to apply for a write lock , The thread applying for the write lock will wait for the read lock to be released ;
3) If a thread has occupied a write lock , At this time, if other threads apply for write lock or read lock , The thread applying will wait for the write lock to be released ;
4) One sentence summary : Either one or more threads have read locks at the same time , Either a thread has a write lock , But the two will not appear at the same time ( Read read share 、 Everything else is mutually exclusive ( Writing mutually exclusive 、 Reading and writing are mutually exclusive 、 Writing and reading are mutually exclusive )).
6. The lock state
stay synchronized The initial implementation of locks is “ Blocking or waking up a thread requires an operating system switch CPU State to complete , This state takes processor time , If the content in the synchronization code block is too simple , This switching may take longer than user code execution ”, This way is synchronized The initial way to achieve synchronization , This is what developers criticized at the beginning , This is also in the JDK6 before synchronized The reason for inefficiency ,JDK6 In order to reduce the performance consumption of acquiring lock and releasing lock , Introduced “ Biased locking ” and “ Lightweight lock ”.
So at present, there are four lock states , The order from low to high is : unlocked 、 Biased locking , Lightweight lock , Heavyweight lock , Lock status can only be upgraded , Can't downgrade .
6.1 unlocked
Unlocked means No locking of resources , All threads can access and modify the same resource , But at the same time, only one thread can modify successfully . The characteristic of no lock is that the modification operation will be carried out in the loop , Threads will constantly try to modify shared resources , If there is no conflict, modify successfully and exit , Otherwise, it's going to keep trying . If multiple threads modify the same value , One thread must be modified successfully , And other threads that fail to modify will continue to retry , Until the modification is successful .
6.2 Biased locking
Biased locking is when a piece of synchronization code is always accessed by the same thread , That is, when there is no competition among multiple threads , Then the thread will automatically obtain the lock during subsequent access , So as to reduce the consumption caused by obtaining locks , Improve performance .
6.3 Lightweight lock
The locking mechanism should not be used as much as possible mutex, Instead, try to complete it in user status code . I'm really not sure , Reuse mutex.
- A small number of kernel mode user mode switching .
- It is not easy to cause thread scheduling .
6.4 Heavyweight lock
The locking mechanism is heavily dependent on OS Provides mutex
- A large number of kernel mode user mode switching
- It's easy to trigger thread scheduling
边栏推荐
- How to explain JS' bind simulation implementation to your girlfriend
- Implement Lmax disruptor queue from scratch (VI) analysis of the principle of disruptor solving pseudo sharing and consumers' elegant stopping
- Visual full link log tracking
- Kwai focuses on regulating the number maintenance behavior in the ways of handling and manuscript washing, and how to purify the content ecology on the we media platform
- How to create a custom 404 error page in WordPress
- [notes for question brushing] binary linked list to integer
- In the second round, 1000 okaleido tiger were sold out in one hour after logging in to binance NFT again
- 伦敦金即时行情带来什么机会?
- 【unity】将unity编辑c#配置为vscode
- Five interesting magic commands in jupyter notebook
猜你喜欢
18张图,直观理解神经网络、流形和拓扑
[unity] configure unity edit C as vscode
Time series prediction | MATLAB realizes time series prediction of TCN time convolution neural network
SystemVerilog join and copy operators
分类预测 | MATLAB实现TCN时间卷积神经网络的时序分类预测
The digitalization of the consumer industry is upgraded to "rigid demand", and weiit's new retail SaaS empowers enterprises!
What are the methods to track the real-time market of London Silver?
将行内元素转换为块元素的方法
Interview shock 69: is TCP reliable? Why?
Techo hub Fuzhou Station dry goods attack | talk with developers about new industrial intelligence technology
随机推荐
Educational Codeforces Round 132 (Rated for Div. 2)【A~C】
Some considerations about ThreadPool
Classification prediction | MATLAB realizes time series classification prediction of TCN time convolution neural network
【刷题笔记】链表内指定区间反转
iNFTnews | 元宇宙购物体验将成为吸引消费者的一大利器
Hash table~
Cookie和Session
Have you seen the management area decoupling architecture? Can help customers solve big problems
【刷题笔记】从链表中删去总和值为零的连续节点
QT static compiler (MinGW compilation)
Copy the table in word to wechat as a picture and send it
快手重点整治搬运、洗稿等方式的养号行为,自媒体平台如何净化内容生态
数字孪生轨道交通:“智慧化”监控疏通城市运行痛点
Charles -- 从0-1教你如何使用抓包工具
Protective copy & stateless
18张图,直观理解神经网络、流形和拓扑
QT静态编译程序(Mingw编译)
B- 树 ~
小程序毕设作品之微信校园浴室预约小程序毕业设计成品(5)任务书
Selenium wire obtains Baidu Index