当前位置:网站首页>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 applicationAll 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 releaseThe resources it occupies .
In the deadlock code above , We usedsynchronizedkeyword , It cannot actively release resources , It will cause the thread to block all the time ,JUC ProvidesLockSolve this problem .
Use... Explicitly Lock Class tryLock Function to replace the built-in locking mechanism , SureDetection of deadlockAnd 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 occupancyIn 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 .
边栏推荐
- Leetcode question brushing record | 283_ Move zero
- Node JS maintains a long connection
- burpsuite
- Redisson分布式锁解锁异常
- 文盘Rust -- 给程序加个日志
- 需要思考的地方
- [knowledge map paper] attnpath: integrate the graph attention mechanism into knowledge graph reasoning based on deep reinforcement
- 金融业数字化转型中,业务和技术融合需要经历三个阶段
- In depth analysis of ArrayList source code, from the most basic capacity expansion principle, to the magic iterator and fast fail mechanism, you have everything you want!!!
- nmap工具介绍及常用命令
猜你喜欢

文盘Rust -- 给程序加个日志

burpsuite

XXL job of distributed timed tasks

银行需要搭建智能客服模块的中台能力,驱动全场景智能客服务升级

Master go game through deep neural network and tree search

牛熊周期与加密的未来如何演变?看看红杉资本怎么说

Nacos microservice gateway component +swagger2 interface generation

Neural network and deep learning-5-perceptron-pytorch

Leetcode featured 200 channels -- array article
![[target tracking] |dimp: learning discriminative model prediction for tracking](/img/72/d151fe0eb0a92e8c6931e6c50dad0f.png)
[target tracking] |dimp: learning discriminative model prediction for tracking
随机推荐
Literature reading and writing
nmap工具介绍及常用命令
牛熊周期与加密的未来如何演变?看看红杉资本怎么说
Talk about the cloud deployment of local projects created by SAP IRPA studio
Exit of processes and threads
How mysql/mariadb generates core files
Leetcode question brushing record | 283_ Move zero
What are the types of system tests? Let me introduce them to you
QT -- create QT program
魚和蝦走的路
Anan's judgment
谈谈 SAP iRPA Studio 创建的本地项目的云端部署问题
The way fish and shrimp go
Clickhouse principle analysis and application practice "reading notes (8)
burpsuite
XMeter Newsletter 2022-06|企业版 v3.2.3 发布,错误日志与测试报告图表优化
2022国内十大工业级三维视觉引导企业一览
Semantic segmentation | learning record (1) semantic segmentation Preface
#797div3 A---C
The generosity of a pot fish