java multithreaded deadlock details and simple examples

  • 2020-05-30 20:17:46
  • OfStack

java multithreaded deadlock

Believe that the multithreaded programming experience of friends, have suffered from deadlock. Unless you don't use multithreading, the possibility of deadlock is always present. Why do deadlocks occur? I think the reasons are as follows:

(1) differences in personal experience of using locks
(2) differences in the use of locks in modules
(3) differences between versions
(4) differences between branches
(5) the difference between modifying the code and refactoring the code

Whatever the cause, there is a danger of deadlocks. So, what are the usual deadlocks? We can look at it one by one,

(1) forget to release the lock


void data_process() 
{ 
  EnterCriticalSection(); 
 
  if(/* error happens */) 
    return; 
 
  LeaveCriticalSection(); 
} 

(2) single thread repeatedly applies for lock


void sub_func() 
{ 
  EnterCriticalSection(); 
  do_something(); 
  LeaveCriticalSection(); 
} 
 
void data_process() 
{ 
  EnterCriticalSection(); 
  sub_func(); 
  LeaveCriticalSection(); 
} 

(3) dual-thread multi-lock application


void data_process1() 
{ 
  EnterCriticalSection(&cs1); 
  EnterCriticalSection(&cs2); 
  do_something1(); 
  LeaveCriticalSection(&cs2); 
  LeaveCriticalSection(&cs1); 
} 
 
void data_process2() 
{ 
  EnterCriticalSection(&cs2); 
  EnterCriticalSection(&cs1); 
  do_something2(); 
  LeaveCriticalSection(&cs1); 
  LeaveCriticalSection(&cs2); 
} 

(4) ring lock application


/* 
*       A  - B 
*       |   | 
*       C  - D 
*/ 

Suppose there are four people, A, B, C and D, eating at the same time. Each person has one chopstick to the left and one to the right. So, if one of them wants to eat, he must first pick up the left chopstick, then pick up the right chopstick. Now, let's get everyone eating at the same time. So that's very likely to happen. Everyone picked up the left chopstick, or everyone picked up the right chopstick, in order to eat, they are now waiting for another chopstick. At this point, everyone wants to eat, and everyone does not want to give up the one chopstick they have already got. So, in fact, no one can eat.

Conclusion:

(1) there is always the danger of deadlock, but we should try to reduce the scope of this hazard
(2) deadlock resolution is extremely expensive
(3) the best way to deal with deadlocks is to detect them as much as possible when writing programs
(4) multithreading is a double-edged sword, with the improvement of efficiency, of course, there is a danger of deadlock
(5) some program deadlocks can be tolerated, even if you restart the machine, but some programs can't

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: