当前位置:网站首页>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

  1. Mutually exclusive , Shared resources X and Y Can only be occupied by one thread ;
  2. 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;
  3. Do not take , Other threads cannot forcibly preempt threads T1 Resources in possession ;
  4. 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 .
img

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 used synchronized keyword , It cannot actively release resources , It will cause the thread to block all the time ,JUC Provides Lock Solve this problem .
    Use... Explicitly Lock Class tryLock Function to replace the built-in locking mechanism , Sure Detection 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 threads Cross 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 .

原网站

版权声明
本文为[Archie_ java]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/189/202207080043203514.html