File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed 
src/main/java/com/rampatra/threads Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change 1+ package  com .rampatra .threads ;
2+ 
3+ 
4+ import  java .lang .management .ManagementFactory ;
5+ import  java .lang .management .ThreadMXBean ;
6+ 
7+ /** 
8+  * @author rampatra 
9+  * @since 2019-03-13 
10+  */ 
11+ public  class  SimpleDeadlock  implements  Runnable  {
12+ 
13+     private  final  Object  obj1 ;
14+     private  final  Object  obj2 ;
15+ 
16+     private  SimpleDeadlock (Object  obj1 , Object  obj2 ) {
17+         this .obj1  = obj1 ;
18+         this .obj2  = obj2 ;
19+     }
20+ 
21+     public  void  run () {
22+         try  {
23+             synchronized  (obj1 ) {
24+                 // sleep for some time so that the next thread starts and acquires the other lock in the mean time 
25+                 Thread .sleep (5000 );
26+                 synchronized  (obj2 ) {
27+                     System .out .println ("No deadlock!" );
28+                 }
29+             }
30+         } catch  (InterruptedException  e ) {
31+             throw  new  RuntimeException (e );
32+         }
33+     }
34+ 
35+     public  static  void  main (String [] args ) {
36+ 
37+         Object  obj1  = new  Object ();
38+         Object  obj2  = new  Object ();
39+ 
40+         Thread  thread1  = new  Thread (new  SimpleDeadlock (obj1 , obj2 ));
41+         Thread  thread2  = new  Thread (new  SimpleDeadlock (obj2 , obj1 ));
42+ 
43+         thread1 .start ();
44+         thread2 .start ();
45+ 
46+         // a way to detect deadlocks, although an expensive one 
47+         ThreadMXBean  threadMXBean  = ManagementFactory .getThreadMXBean ();
48+         while  (true ) {
49+             long [] deadlock  = threadMXBean .findDeadlockedThreads ();
50+             if  (deadlock  != null  && deadlock .length  > 0 ) {
51+                 System .out .println ("Deadlock detected, exiting now..." );
52+                 System .exit (1 );
53+             }
54+         }
55+     }
56+ }
    
 
   
 
     
   
   
          
     
  
    
     
 
    
      
     
 
     
    You can’t perform that action at this time.
  
 
    
  
     
    
      
        
     
 
       
      
     
   
 
    
    
  
 
  
 
     
    
0 commit comments