当前位置:网站首页>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 .
边栏推荐
- "Hands on learning in depth" Chapter 2 - preparatory knowledge_ 2.2 data preprocessing_ Learning thinking and exercise answers
- JVM memory and garbage collection-3-direct memory
- leetcode 869. Reordered Power of 2 | 869. Reorder to a power of 2 (state compression)
- 力扣4_412. Fizz Buzz
- [target tracking] |atom
- Exit of processes and threads
- 2022年5月互联网医疗领域月度观察
- Ml self realization / logistic regression / binary classification
- Leetcode question brushing record | 485_ Maximum number of consecutive ones
- Anan's judgment
猜你喜欢
Deeppath: a reinforcement learning method of knowledge graph reasoning
I don't know. The real interest rate of Huabai installment is so high
Nmap tool introduction and common commands
Talk about the realization of authority control and transaction record function of SAP system
Master go game through deep neural network and tree search
JVM memory and garbage collection -4-string
[knowledge atlas paper] minerva: use reinforcement learning to infer paths in the knowledge base
leetcode 866. Prime Palindrome | 866. 回文素数
leetcode 865. Smallest Subtree with all the Deepest Nodes | 865.具有所有最深节点的最小子树(树的BFS,parent反向索引map)
Why did MySQL query not go to the index? This article will give you a comprehensive analysis
随机推荐
adb工具介绍
Talk about the realization of authority control and transaction record function of SAP system
[knowledge map paper] r2d2: knowledge map reasoning based on debate dynamics
#797div3 A---C
Node JS maintains a long connection
喜欢测特曼的阿洛
CV2 read video - and save image or video
XXL job of distributed timed tasks
分布式定时任务之XXL-JOB
Anan's judgment
cv2读取视频-并保存图像或视频
银行需要搭建智能客服模块的中台能力,驱动全场景智能客服务升级
Leetcode featured 200 -- linked list
Redismission source code analysis
Ml self realization / logistic regression / binary classification
For friends who are not fat at all, nature tells you the reason: it is a genetic mutation
See how names are added to namespace STD from cmath file
Uniapp one click Copy function effect demo (finishing)
Literature reading and writing
Ml backward propagation