当前位置:网站首页>Thread deadlock -- conditions for deadlock generation
Thread deadlock -- conditions for deadlock generation
2022-07-08 02:14:00 【Archie_ java】
What is thread deadlock
Thread deadlock refers to two or more threads holding each other's required resources , Cause these threads to wait for each other , If there is no external force , They will not be able to continue .
The cause of deadlock can be summed up in three sentences :
- Current thread Have Resources required by other threads
- Current thread wait for Resources already owned by other threads
- all Don't give up Own resources
Four necessary conditions for thread deadlock
- Mutually exclusive , Shared resources X and Y Can only be occupied by one thread ;
- To possess and wait for , Threads T1 Shared resources have been obtained X, Waiting to share resources Y When , Don't release shared resources X;
- Do not take , Other threads cannot forcibly preempt threads T1 Resources in possession ;
- Loop waiting for , Threads T1 Wait for thread T2 Resources in possession , Threads T2 Wait for thread T1 Resources in possession , It's a cycle of waiting .
For example, deadlock is inevitable
public static void main(String[] args) {
Object a = new Object();
Object b = new Object();
// Threads 1
new Thread(() -> {
synchronized (a) {
System.out.println(" To obtain the A lock ");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (b) {
}
}
}).start();
// Threads 2
new Thread(() -> {
synchronized (b) {
System.out.println(" To obtain the B lock ");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (a) {
}
}
}).start();
}
The above program is a typical example of deadlock , To ensure the probability of deadlock , I slept here after getting the lock 1s.
Threads 1 In obtaining A Wait after the object lock 1s To try to get B Object lock , At this time Threads 1 Is holding A Object lock
Of ; Threads 2 In obtaining B Wait after object lock 1s Try to get A Object lock , At this time Threads 2 Is holding B Object lock
Of ; Just when they want to get each other's lock , Deadlock
It happened. , And it goes on .
How to avoid deadlock
As mentioned above, deadlock will occur only when these four conditions occur , So that means , As long as we destroy one of them , Deadlock can be successfully prevented .
- Destroy mutual exclusion : Only one lock , This is the most critical reason for deadlock . obviously , If we can run before two threads , It can copy a copy of the key for each thread , It can effectively avoid deadlock .
- Occupy and wait :
One time application
All the resources , So there is no waiting .
For example, threads 1 Get it all at once A and B Two locks , Threads 2 When acquiring a lock, you need to wait for the thread 1 Release the lock , This avoids the situation that multiple threads occupy each other and wait . - Do not take : When a thread occupying some resources further requests other resources , If the application does not arrive , Sure
Active release
The resources it occupies .
In the deadlock code above , We usedsynchronized
keyword , It cannot actively release resources , It will cause the thread to block all the time ,JUC ProvidesLock
Solve this problem .
Use... Explicitly Lock Class tryLock Function to replace the built-in locking mechanism , SureDetection of deadlock
And recover from the deadlock . An explicit lock can specify a timeout period (Timeout), After waiting for more than this time tryLock A failure message will be returned , Release the resources they have , Other threads can obtain this resource to avoid deadlock . - Loop waiting for : If a thread needs some locks , Then it must acquire locks in a certain order . Only after obtaining the lock in front in order , To get the back lock .
Breaking the cycle condition is simple , As long as there are no threadsCross occupancy
In case of , That is to say, try to avoid Threads 1 keep A request B, Threads 2 keep B request A, Try to make their requests in the same order , Like threads 1 The order of requests is A、B, Threads 2 The order of requests is also A、B, This naturally avoids the occurrence of circular waiting .
summary
Deadlock is a headache , But as long as our code specification , It can avoid deadlock in most cases . And the classic algorithm to avoid deadlock is the banker algorithm , I won't expand the introduction here .
In many cases , Especially in multithreaded programming , We should pay attention to whether the resources between threads compete with each other , If there is , Avoid the risk of deadlock in time .
Deadlocks often occur in database operations , For example, long transactions 、 Shared lock escalation under concurrent conditions will cause database deadlock , I will talk about database deadlock later .
边栏推荐
- Exit of processes and threads
- Direct addition is more appropriate
- Introduction to Microsoft ad super Foundation
- 云原生应用开发之 gRPC 入门
- Why did MySQL query not go to the index? This article will give you a comprehensive analysis
- Many friends don't know the underlying principle of ORM framework very well. No, glacier will take you 10 minutes to hand roll a minimalist ORM framework (collect it quickly)
- 常见的磁盘格式以及它们之间的区别
- metasploit
- The body has a mysterious margin of 8px
- How mysql/mariadb generates core files
猜你喜欢
LeetCode精选200道--数组篇
很多小伙伴不太了解ORM框架的底层原理,这不,冰河带你10分钟手撸一个极简版ORM框架(赶快收藏吧)
2022年5月互联网医疗领域月度观察
咋吃都不胖的朋友,Nature告诉你原因:是基因突变了
Deeppath: a reinforcement learning method of knowledge graph reasoning
力争做到国内赛事应办尽办,国家体育总局明确安全有序恢复线下体育赛事
Nacos microservice gateway component +swagger2 interface generation
burpsuite
C language -cmake cmakelists Txt tutorial
leetcode 865. Smallest Subtree with all the Deepest Nodes | 865. The smallest subtree with all the deepest nodes (BFs of the tree, parent reverse index map)
随机推荐
鱼和虾走的路
Wechat applet uniapp page cannot jump: "navigateto:fail can not navigateto a tabbar page“
[recommendation system paper reading] recommendation simulation user feedback based on Reinforcement Learning
VIM use
#797div3 A---C
Keras深度学习实战——基于Inception v3实现性别分类
Can you write the software test questions?
LeetCode精选200道--链表篇
很多小伙伴不太了解ORM框架的底层原理,这不,冰河带你10分钟手撸一个极简版ORM框架(赶快收藏吧)
COMSOL --- construction of micro resistance beam model --- final temperature distribution and deformation --- addition of materials
The body has a mysterious margin of 8px
Clickhouse principle analysis and application practice "reading notes (8)
Talk about the realization of authority control and transaction record function of SAP system
ClickHouse原理解析与应用实践》读书笔记(8)
"Hands on learning in depth" Chapter 2 - preparatory knowledge_ 2.2 data preprocessing_ Learning thinking and exercise answers
cv2读取视频-并保存图像或视频
CV2 read video - and save image or video
For friends who are not fat at all, nature tells you the reason: it is a genetic mutation
常见的磁盘格式以及它们之间的区别
If time is a river