Advertisement
DulcetAirman

Java deadlock demo

Jun 1st, 2014
285
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package com.example.foo;
  2.  
  3. import java.util.concurrent.ExecutorService;
  4. import java.util.concurrent.Executors;
  5. import java.util.concurrent.TimeUnit;
  6.  
  7. public class SomeClass {
  8.   static class Outer {
  9.     Inner inner = new Inner();
  10.  
  11.     public synchronized String getBoth() {
  12.       return this.toString() + " - " + this.inner.toString();
  13.     }
  14.  
  15.     class Inner {
  16.       public synchronized String getBoth() {
  17.         return this.toString() + " - " + Outer.this.toString();
  18.       }
  19.  
  20.       @Override
  21.       public synchronized String toString() {
  22.         Thread.yield(); // To increase risk of deadlock
  23.         return "Inner";
  24.       }
  25.     }
  26.  
  27.     @Override
  28.     public synchronized String toString() {
  29.       Thread.yield(); // To increase risk of deadlock
  30.       return "Outer";
  31.     }
  32.   }
  33.  
  34.   public static void main(String[] args) throws InterruptedException {
  35.     final Outer o = new Outer();
  36.     // No problem:
  37.     System.out.println(o.getBoth()); // outer, inner
  38.     System.out.println(o.inner.getBoth()); // inner, outer
  39.  
  40.     ExecutorService pool = Executors.newFixedThreadPool(4);
  41.     for (int i = 0; i < 100; i++) {
  42.       pool.execute(() -> {
  43.         System.out.println(o.getBoth());
  44.       });
  45.       pool.execute(() -> {
  46.         System.out.println(o.inner.getBoth());
  47.       });
  48.     }
  49.     pool.shutdown();
  50.     if (!pool.awaitTermination(10, TimeUnit.SECONDS))
  51.       throw new RuntimeException("DEADLOCK!");
  52.  
  53.     System.out.println("END");
  54.   }
  55.  
  56. }
Advertisement
Advertisement
Advertisement
RAW Paste Data Copied
Advertisement