SlideShare a Scribd company logo
1 of 180
Download to read offline
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




              Deadlock Victim
           by Dr Heinz Kabutz     &&   Olivier Croisier
The Java Specialists Newsletter   &&   The Coder's Breakfast
       heinz@javaspecialists.eu   &&   olivier.croisier@zenika.com
         twitter: @heinzkabutz    &&   twitter: @oliviercroisier




                                                                       1
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




You discover a race condition



                                                                     2
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




  Data is being corrupted



                                                                    3
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




        What ya gonna do?



                                                                    4
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




        Who ya gonna call?



                                                                    5
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




              Ghostbusters?



                                                                    6
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




    you do what we all do



                                                                    7
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




 you use synchronized



                                                                    8
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




           synchronized



                                                                    9
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




           synchronized



                                                                    9
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




synchronized can be bad
       medicine



                                                                    10
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




   deadlock awaits you!



                                                                    11
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




                                                                    12
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




         Deadlock Victim



                                                                    13
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




            Correctness fix
              can lead to
             liveness fault

                                                                    14
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




   lock ordering deadlock



                                                                    15
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




          at least two locks



                                                                    16
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




 and at least two threads



                                                                    17
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




locked in different orders



                                                                    18
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




can cause a deadly embrace



                                                                    19
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




requires global analysis to fix



                                                                     20
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




       resource deadlocks



                                                                    21
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




           bounded queues



                                                                    22
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




    bounded thread pools



                                                                    23
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




                 semaphores



                                                                    24
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




                class loaders



                                                                    25
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




                  lost signals



                                                                    26
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




The Drinking Philosophers



                                                                    27
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




@ the Java Specialist Symposium
            in Crete



                                                                       28
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




Symposium == sym + poto
                 Literally - to drink together




                                                                    29
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




our philosophers need two cups



                                                                       30
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




they either want to drink or think



                                                                        31
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr

Table is ready, all philosophers are
              thinking
                                    1



                  5                                   2




                        4                      3
                                                                        32
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr

philosophers 5 wants to drink,
       takes right cup
                                  1



                5                                   2




                      4                      3
                                                                      33
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr

Philosopher 5 is now drinking with
            both cups
                                    1



                  5                                   2




                        4                      3
                                                                        34
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr

philosophers 3 wants to drink,
       takes right cup
                                  1



                5                                   2




                      4                      3
                                                                      35
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr

Philosopher 3 is now drinking with
            both cups
                                    1



                  5                                   2




                        4                      3
                                                                        36
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr

philosophers 2 wants to drink,
       takes right cup
                                  1



                5                                   2




                      4                      3
                                                                      37
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr

Philosopher 3 finished drinking,
       returns right cup
                                  1



                5                                   2




                      4                      3
                                                                      38
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr

Philosopher 2 is now drinking with
            both cups
                                    1



                  5                                   2




                        4                      3
                                                                        39
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



Philosopher 3 returns Left cup
                                  1



                5                                   2




                      4                      3
                                                                      40
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




philosophers can get stuck



                                                                    41
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




if they all pick up the right cup



                                                                      42
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr

A deadlock can easily happen with
           this design
                                    1



                  5                                   2




                        4                      3
                                                                        43
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr

Philosopher 5 wants to drink, takes
            right cup
                                    1



                  5                                   2




                        4                      3
                                                                        44
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr

Philosopher 1 wants to drink, takes
            right cup
                                    1



                  5                                   2




                        4                      3
                                                                        45
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr

Philosopher 2 wants to drink, takes
            right cup
                                    1



                  5                                   2




                        4                      3
                                                                        46
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr

Philosopher 3 wants to drink, takes
            right cup
                                    1



                  5                                   2




                        4                      3
                                                                        47
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr

Philosopher 4 wants to drink, takes
            right cup
                                    1



                  5                                   2




                        4                      3
                                                                        48
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



                   Deadlock!
                                1



              5                                   2




                    4                      3
                                                                    49
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



   they will all stay thirsty
                                1



              5                                   2




                    4                      3
                                                                    50
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



   this is a deadly embrace
                                1



              5                                   2




                    4                      3
                                                                    51
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




this can be detected automatically



                                                                        52
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




search the graph of call stacks



                                                                      53
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




and look for circular dependencies



                                                                        54
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




ThreadMXBean does that for us



                                                                      55
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




simple deadlocks are quickly found



                                                                        56
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




but what do you DO with them?



                                                                       57
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




what will the dog do with the car if
        he ever catches it?



                                                                        58
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




databases choose deadlock victim



                                                                       59
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




   but what does Java do?



                                                                    60
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




it should probably throw an Error



                                                                        61
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




but the threads simply hang up



                                                                      62
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




it is best to avoid causing them!



                                                                       63
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




global order of locks in program



                                                                       64
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr

public class LeftRightDeadlock {
  private final Object left = new Object();
  private final Object right = new Object();
  public void leftRight() {
    synchronized (left) {
      synchronized (right) {
        doSomething();
      }
    }
  }
  public void rightLeft() {
    synchronized (right) {
      synchronized (left) {
        doSomethingElse();
      }
    }
  }
}

                                                                          65
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



    Interleaving causes deadlock
                  lock left                      trying to lock right

A   leftRight()                                     BLOCKED



                                       lock right          trying to lock left


B                      rightLeft()                            BLOCKED




                                                                                 66
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




we define a fixed global order



                                                                     67
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




       e.g. left before right



                                                                    68
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




        deadlock is solved!
     public void rightLeft() {
       synchronized (left) {
         synchronized (right) {
           doSomethingElse();
         }
       }
     }
                                                                    69
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




our drinking philosophers



                                                                    70
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




each cup gets a unique number



                                                                      71
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




lock the highest number cup first



                                                                       72
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




then lock the lower number cup



                                                                       73
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




                         drink



                                                                    74
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




  unlock lower order cup



                                                                    75
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




 unlock higher order cup



                                                                    76
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




                          think



                                                                    77
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



                Global Lock ordering
•   We start with all the                  1
    philosophers thinking
                                       1          2
                         5                                   2


                                   5                  3


                                           4

                               4                      3
                                                                               78
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



           Philosopher 5 takes cup 5
• Cup 5 has higher number                   1

 • Remember our rule!
                                      1            2
                          5                                   2
                              5
                                                       3


                                            4

                                  4                    3
                                                                                79
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



              Philosopher 1 takes cup 2
• Must take the cup with                      1
  the higher number                                2
  first
                                        1
 •   In this case           5                                   2
     cup 2                      5
                                                        3


                                              4

                                    4                    3
                                                                                  80
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



Philosopher 2 takes cup 3
                                1
                                     2

                          1
              5                                   2
                  5                             3



                                4

                      4                    3
                                                                    81
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



Philosopher 3 takes cup 4
                                1
                                     2

                          1
              5                                   2
                  5                             3




                      4              4     3
                                                                    82
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr

Philosopher 1 takes cup 1 -
         Drinking
                                1
                           1         2


              5                                   2
                  5                             3




                      4              4     3
                                                                    83
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



         Philosopher 1 returns Cup 1
• Cups are returned in the                 1
  opposite order to what                        2
  they are acquired
                                     1
                         5                                   2
                             5                             3




                                 4              4     3
                                                                               84
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr

Philosopher 5 takes cup 1 -
         Drinking
                                1
                                     2
                      1

              5                                   2
                  5                             3




                      4              4     3
                                                                    85
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



Philosopher 5 returns cup 1
                                 1
                                      2

                           1
               5                                   2
                   5                             3




                       4              4     3
                                                                     86
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



Philosopher 1 returns cup 2
                                 1


                           1              2
               5                                   2
                   5                              3




                       4              4       3
                                                                     87
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr

Philosopher 2 takes cup 2 -
         Drinking
                                1

                                               2
                          1
              5                                    2
                  5                                3




                      4              4     3
                                                                    88
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



Philosopher 5 returns cup 5
                                 1

                                                2
                             1
               5                                    2
                                                    3
                         5




                     4                4     3
                                                                     89
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



Philosopher 4 takes cup 5
                                1

                                               2
                          1
              5                                    2
                                                   3


                  5


                      4              4     3
                                                                    90
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



Philosopher 2 returns cup 2
                                 1


                           1              2
               5                                   2
                                                  3


                   5


                       4              4       3
                                                                     91
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



Philosopher 2 returns cup 3
                                 1


                           1              2
               5                                   2


                                              3

                   5


                       4              4       3
                                                                     92
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr

Philosopher 3 takes cup 3 -
         Drinking
                                1


                          1              2
              5                                      2



                  5                              3


                      4              4       3
                                                                    93
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



Philosopher 3 Returns cup 3
                                 1


                           1              2
               5                                   2


                                              3

                   5


                       4              4       3
                                                                     94
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



Philosopher 3 Returns cup 4
                                 1


                           1            2
               5                                   2


                                            3

                   5
                                 4

                       4                    3
                                                                     95
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr

Philosopher 4 takes cup 4 -
         Drinking
                                  1


                          1            2
              5                                   2


                                           3

                  5


                      4       4
                                           3
                                                                    96
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



Philosopher 4 Returns cup 4
                                 1


                           1            2
               5                                   2


                                            3

                   5
                                 4

                       4                    3
                                                                     97
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



Philosopher 4 Returns cup 5
                                 1


                             1          2
               5                                   2


                         5                  3


                                 4

                     4                      3
                                                                     98
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




sorting locks by property is easy



                                                                       99
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




e.g. account IBAN number



                                                                    100
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




     or employee number



                                                                    101
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




or some other characteristic



                                                                     102
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




       maybe even
System.identityHashCode()



                                                                    103
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




            use "open calls"



                                                                    104
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




 Vector synchronizes writeObject()
private synchronized void writeObject(ObjectOutputStream s)
    throws IOException {
  s.defaultWriteObject();
}



                                                                            105
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




    synchronized writeObject() is
   invoking s.defaultWriteObject()
private synchronized void writeObject(ObjectOutputStream s)
    throws IOException {
  s.defaultWriteObject();
}



                                                                            106
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




          this is not an "open call"
private synchronized void writeObject(ObjectOutputStream s)
    throws IOException {
  s.defaultWriteObject();
}



                                                                            107
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




        but can it cause problems?
private synchronized void writeObject(ObjectOutputStream s)
    throws IOException {
  s.defaultWriteObject();
}



                                                                            108
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




                           yes it can!
private synchronized void writeObject(ObjectOutputStream s)
    throws IOException {
  s.defaultWriteObject();
}



                                                                            109
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




serialize both vectors at same time
Vector v1 = new Vector();
Vector v2 = new Vector();
v1.add(v2);
v2.add(v1);



                                                                            110
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




this could happen with nested data
             structures



                                                                        111
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




it happened to an IBM client



                                                                     112
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr
private void writeObject(ObjectOutputStream stream)
    throws IOException {
  Vector<E> cloned = null;
  // this specially fix is for a special dead-lock in customer
  // program: two vectors refer each other may meet dead-lock in
  // synchronized serialization. Refer CMVC-103316.1
  synchronized (this) {
    try {
      cloned = (Vector<E>) super.clone();
      cloned.elementData = elementData.clone();
    } catch (CloneNotSupportedException e) {
      // no deep clone, ignore the exception
    }
  }
  cloned.writeObjectImpl(stream);
}

private void writeObjectImpl(ObjectOutputStream stream)
   throws IOException {
 stream.defaultWriteObject();
}
                                                                                113
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




          Java 7 uses an "open call"
private void writeObject(ObjectOutputStream s)
    throws IOException {
  final ObjectOutputStream.PutField fields = s.putFields();
  final Object[] data;
  synchronized (this) {
    fields.put("capacityIncrement", capacityIncrement);
    fields.put("elementCount", elementCount);
    data = elementData.clone();
  }
  fields.put("elementData", data);
  s.writeFields();
}
                                                                              114
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



More synchronized writeObject()s
•   File

•   StringBuffer

•   Throwable

•   URL

•   Hashtable

•   and others

                                                                               115
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




we have seen the deadly embrace



                                                                       116
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




are there other deadlocks?



                                                                    117
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




     semaphore deadlocks



                                                                    118
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



    Bounded DB Connection Pools

•   For example, say you have two DB connection pools

    •   Some tasks might require connections to both databases

    •   Thus thread A might hold semaphore for D1 and wait for D2,
        whereas thread B might hold semaphore for D2 and be waiting for
        D1



                                                                                119
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr

public class DatabasePool {
  private final Semaphore connections;
  public DatabasePool(int connections) {
    this.connections = new Semaphore(connections);
  }

    public void connect() {
      connections.acquireUninterruptibly();
      System.out.println("DatabasePool.connect");
    }

    public void disconnect() {
      System.out.println("DatabasePool.disconnect");
      connections.release();
    }
}
                                                                              120
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




ThreadMXBean does not show
     this as a deadlock!



                                                                      121
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



JVM does not detect this deadlock




                                                                        122
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



JVM does not detect this deadlock




                                                                        122
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




Avoiding and diagnosing deadlocks
                      Avoiding Liveness Hazards




                                                                        123
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



Avoiding and diagnosing deadlocks


•   You cannot get a lock-ordering deadlock with a single lock

    •   Easiest way to avoid deadlocks

    •   But not always practical




                                                                                124
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



Avoiding and diagnosing deadlocks

•   For multiple locks we need to define a lock order

    •   specify and document possible lock sequences

    •   Identify where multiple locks could be acquired

    •   Do a global analysis to ensure that lock ordering is consistent

        •   This can be extremely difficult in large programs


                                                                                   125
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




Use open calls whenever possible



                                                                       126
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr

        Unit Testing for lock ordering
                  deadlocks

•   Code typically has to be called many times before a deadlock happens

•   How many times do you need to call it to prove that there is no
    deadlock?

    •   Nondeterministic unit tests are bad - they should either always pass
        or always fail



                                                                                127
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



                         Testing the Bank
    •   In the transferMoney() method, a deadlock occurs if after the first
        lock is granted, the first thread is swapped out and another thread
        requests the second lock
public class Bank {
  public boolean transferMoney(Account from, Account to, Amount amount) {
    synchronized (from) {
      // if thread is swapped out here, we can end up with a deadlock
      synchronized (to) {
        return doActualTransfer(from, to, amount);
      }
    }
  }
}
                                                                                  128
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




We can force the context switch



                                                                       129
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




simply add a sleep after first lock



                                                                       130
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



Adding a sleep to cause deadlocks
public class Bank {
  public boolean transferMoney(Account from, Account to,
                               Amount amount) {
    synchronized (from) {
      sleepAWhileForTesting();
      synchronized (to) {
        return doActualTransfer(from, to, amount);
      }
    }
  }
  protected void sleepAWhileForTesting() {}
}

                                                                           131
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



In our unit test we use a SlowBank
   public class SlowBank extends Bank {
     private final long timeout;
     private final TimeUnit unit;
     public SlowBank(long timeout, TimeUnit unit) {
       this.timeout = timeout;
       this.unit = unit;
     }
     protected void sleepAWhileForTesting() {
       try {
         unit.sleep(timeout);
       } catch (InterruptedException e) {
         Thread.currentThread().interrupt();
       }
     }
   }
                                                                         132
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




Won't this cause problems in
        production?



                                                                     133
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




In production we only use Bank



                                                                      134
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




HotSpot will optimize away empty
    sleepAWhileForTesting()



                                                                        135
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




      it is thus a zero cost



                                                                    136
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




as long as SlowBank is never used



                                                                       137
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




How can you verify the lock-
   ordering deadlock?



                                                                     138
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




CTRL+Break, jstack, kill -3,
     jconsole, etc.



                                                                    139
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




but that won't be a good unit test



                                                                        140
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




Better via Java's ThreadMXBean



                                                                      141
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



                        ThreadMXBean

•   Get instance with ManagementFactory.getThreadMXBean()

•   findMonitorDeadlockedThreads()

    •   Includes only "monitor" locks, i.e. synchronized

    •   Only way to find deadlocks in Java 5



                                                                                142
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



                        ThreadMXBean

•   Better is findDeadlockedThreads()

    •   Includes "monitor" and "owned" (Java 5) locks

    •   Preferred method to test for deadlocks

    •   But, does not find deadlocks between semaphores

•   See http://www.javaspecialists.eu/archive/Issue130.html


                                                                                143
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




public class BankDeadlockTest {
  private final static ThreadMXBean tmb =
    ManagementFactory.getThreadMXBean();

 private boolean isThreadDeadlocked(long tid) {
   long[] ids = tmb.findDeadlockedThreads();
   if (ids == null) return false;
   for (long id : ids) {
     if (id == tid) return true;
   }
   return false;
 }




                                                                      144
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




private void checkThatThreadTerminates(Thread thread)
    throws InterruptedException {
  for (int i = 0; i < 2000; i++) {
    thread.join(50);
    if (!thread.isAlive()) return;
    if (isThreadDeadlocked(thread.getId())) {
      fail("Deadlock detected!");
    }
  }
  fail(thread + " did not terminate in time");
}




                                                                        145
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr
    @Test
    public void testForTransferDeadlock() throws InterruptedException {
      final Account alpha = new Account(new Amount(1000));
      final Account ubs = new Account(new Amount(1000000));
      final Bank bank = new SlowBank(100, TimeUnit.MILLISECONDS);

        Thread alphaToUbs = new Thread("alphaToUbs") {
          public void run() {
            bank.transferMoney(alpha, ubs, new Amount(100));
          }
        };
        Thread ubsToAlpha = new Thread("ubsToAlpha") {
          public void run() {
            bank.transferMoney(ubs, alpha, new Amount(100));
          }
        };

        alphaToUbs.start();
        ubsToAlpha.start();

        checkThatThreadTerminates(alphaToUbs);
    }
}
                                                                                    146
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr

                 Output with broken
               transferMoney() method
     •   We see the deadlock within about 100 milliseconds
junit.framework.AssertionFailedError: Deadlock detected!
  at BankDeadlockTest.checkThatThreadTerminates(BankDeadlockTest.java:20)
  at BankDeadlockTest.testForTransferDeadlock(BankDeadlockTest.java:55)




                                                                                  147
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr

               Output with broken
             transferMoney() method

•   If we fix the transferMoney() method, it also completes within about
    100 milliseconds

    •   This is the time that we are sleeping for testing purposes

•   Remember that the empty sleepAWhileForTesting() method will be
    optimized away by HotSpot



                                                                                148
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



                Timed lock attempts


•   Another technique for solving deadlocks is to use the timed tryLock()
    method of explicit Java locks




                                                                              149
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




However, if tryLock() fails it may be



                                                                         150
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




                  a deadlock



                                                                    151
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




or some thread taking a long time



                                                                        152
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




or a thread in an infinite loop



                                                                     153
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




But ThreadMXBean shows it as
          deadlocked



                                                                      154
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




even if it is a temporary condition



                                                                        155
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




The JVM has support for tryLock
      with synchronized



                                                                       156
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




      but it is hidden away



                                                                    157
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




                 So here it is



                                                                    158
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




                                                                    159
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




   Told you it was hidden!



                                                                    160
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




It is hidden for a good reason



                                                                     161
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




if you need tryLock functionality



                                                                       162
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




   rather use explicit locks
      (ReentrantLock)



                                                                    163
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



           tryLock with synchronized

•   Technically possible in Sun JVM using

    •   Unsafe.getUnsafe().tryMonitorEnter(monitor)

    •   Unsafe.getUnsafe().monitorExit(monitor)

•   http://www.javaspecialists.eu/archive/Issue194.html



                                                                                164
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




Deadlock analysis with thread
          dumps



                                                                      165
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr

            Deadlock analysis with thread
                      dumps
•   We can also cause a thread dump in many ways:

    •   Ctrl+Break on Windows or Ctrl- on Unix

    •   Invoking "kill -3" on the process id

    •   Calling jstack on the process id

        •   Only shows deadlocks since Java 6

•   Intrinsic locks show more information of where they were acquired

                                                                                  166
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




Can a deadlock be resolved?



                                                                     167
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




   NO with synchronized



                                                                    168
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




 YES with ReentrantLock



                                                                    169
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




 synchronized() goes into
     BLOCKED state



                                                                    170
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




ReentrantLock.lock() goes into
       WAITING state



                                                                      171
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




We can write a DealockArbitrator



                                                                        172
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




This stops one of the threads with
      a DeadlockVictimError



                                                                        173
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



Our special Error for deadlocks
 public class DeadlockVictimError extends Error {
   private final Thread victim;
   public DeadlockVictimError(Thread victim) {
     super("Deadlock victim: " + victim);
     this.victim = victim;

     }
     public Thread getVictim() { return victim; }
 }




                                                                         174
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr
public class DeadlockArbitrator {
  private static final ThreadMXBean tmb =
      ManagementFactory.getThreadMXBean();

 public boolean tryResolveDeadlock(
     int attempts, long timeout, TimeUnit unit)
     throws InterruptedException {
   for (int i = 0; i < attempts; i++) {
     long[] ids = tmb.findDeadlockedThreads();
     if (ids == null) return true;
     Thread t = findThread(ids[i % ids.length]);
     if (t == null)
       throw new IllegalStateException("Could not find thread");
     t.stop(new DeadlockVictimError(t));
     unit.sleep(timeout);
   }
   return false;
 }
                                                                                175
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



            finding threads by id is tricky
    public boolean tryResolveDeadlock() throws InterruptedException {
      return tryResolveDeadlock(3, 1, TimeUnit.SECONDS);
    }

    private Thread findThread(long id) {
      for (Thread thread : Thread.getAllStackTraces().keySet()) {
        if (thread.getId() == id) return thread;
      }
      return null;
    }
}



                                                                                  176
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr



Applicability of DeadlockArbitrator

•   Only use in extreme circumstances

    •   Code that is outside your control and that deadlocks

    •   Where you cannot prevent the deadlock

•   Remember, it only works with ReentrantLock



                                                                                177
The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr




Deadlock Victim Questions?
           by Dr Heinz Kabutz     &&   Olivier Croisier
The Java Specialists Newsletter   &&   The Coder's Breakfast
       heinz@javaspecialists.eu   &&   olivier.croisier@zenika.com
         twitter: @heinzkabutz    &&   twitter: @oliviercroisier




                                                                       178

More Related Content

Viewers also liked

Didactica universitaria
Didactica universitariaDidactica universitaria
Didactica universitariacrojas6
 
Supp. Lesson - The Holy Spirit Sustains the Church as She Grows (CLE 7 - CSQC)
Supp. Lesson -  The Holy Spirit Sustains the Church as She Grows (CLE 7 - CSQC)Supp. Lesson -  The Holy Spirit Sustains the Church as She Grows (CLE 7 - CSQC)
Supp. Lesson - The Holy Spirit Sustains the Church as She Grows (CLE 7 - CSQC)Arvin Lising
 
E Pouch 2012 Designs
E Pouch 2012 DesignsE Pouch 2012 Designs
E Pouch 2012 DesignsTomTranter
 
Healthy lifestyle's education - retrospectiva
Healthy lifestyle's education - retrospectivaHealthy lifestyle's education - retrospectiva
Healthy lifestyle's education - retrospectivacecisromania
 
University Square Stratford
University Square StratfordUniversity Square Stratford
University Square StratfordMarkBradbury
 
Otras teorias de donde somos
Otras teorias de donde somosOtras teorias de donde somos
Otras teorias de donde somosArturo Zamorano
 
Empreendedorismo nos games marketing de nicho
Empreendedorismo nos games   marketing de nichoEmpreendedorismo nos games   marketing de nicho
Empreendedorismo nos games marketing de nichoJulio Matos
 
Fête langouste-Pérez Taia
Fête langouste-Pérez Taia Fête langouste-Pérez Taia
Fête langouste-Pérez Taia kedougou
 
Personal Leadership rev 1
Personal Leadership rev 1Personal Leadership rev 1
Personal Leadership rev 1Rachmat Gunawan
 
Demand-Driven Acquisition in the Colorado Alliance of Research Libraries
Demand-Driven Acquisition in the Colorado Alliance of Research LibrariesDemand-Driven Acquisition in the Colorado Alliance of Research Libraries
Demand-Driven Acquisition in the Colorado Alliance of Research LibrariesMichael Levine-Clark
 
Double page spread research
Double page spread researchDouble page spread research
Double page spread researchbeealex
 
hierarki nilai sikap-tingkah laku
hierarki nilai sikap-tingkah lakuhierarki nilai sikap-tingkah laku
hierarki nilai sikap-tingkah lakumahasiswaUI
 

Viewers also liked (19)

Didactica universitaria
Didactica universitariaDidactica universitaria
Didactica universitaria
 
Supp. Lesson - The Holy Spirit Sustains the Church as She Grows (CLE 7 - CSQC)
Supp. Lesson -  The Holy Spirit Sustains the Church as She Grows (CLE 7 - CSQC)Supp. Lesson -  The Holy Spirit Sustains the Church as She Grows (CLE 7 - CSQC)
Supp. Lesson - The Holy Spirit Sustains the Church as She Grows (CLE 7 - CSQC)
 
5 g racing over research
5 g racing over research5 g racing over research
5 g racing over research
 
Exodus media
Exodus mediaExodus media
Exodus media
 
Ancillary tasks
Ancillary tasksAncillary tasks
Ancillary tasks
 
E Pouch 2012 Designs
E Pouch 2012 DesignsE Pouch 2012 Designs
E Pouch 2012 Designs
 
Healthy lifestyle's education - retrospectiva
Healthy lifestyle's education - retrospectivaHealthy lifestyle's education - retrospectiva
Healthy lifestyle's education - retrospectiva
 
University Square Stratford
University Square StratfordUniversity Square Stratford
University Square Stratford
 
Otras teorias de donde somos
Otras teorias de donde somosOtras teorias de donde somos
Otras teorias de donde somos
 
Empreendedorismo nos games marketing de nicho
Empreendedorismo nos games   marketing de nichoEmpreendedorismo nos games   marketing de nicho
Empreendedorismo nos games marketing de nicho
 
Tunneling Repair
Tunneling RepairTunneling Repair
Tunneling Repair
 
Fête langouste-Pérez Taia
Fête langouste-Pérez Taia Fête langouste-Pérez Taia
Fête langouste-Pérez Taia
 
Personal Leadership rev 1
Personal Leadership rev 1Personal Leadership rev 1
Personal Leadership rev 1
 
Actp010
Actp010Actp010
Actp010
 
Demand-Driven Acquisition in the Colorado Alliance of Research Libraries
Demand-Driven Acquisition in the Colorado Alliance of Research LibrariesDemand-Driven Acquisition in the Colorado Alliance of Research Libraries
Demand-Driven Acquisition in the Colorado Alliance of Research Libraries
 
Hammer timeline
Hammer timelineHammer timeline
Hammer timeline
 
Double page spread research
Double page spread researchDouble page spread research
Double page spread research
 
hierarki nilai sikap-tingkah laku
hierarki nilai sikap-tingkah lakuhierarki nilai sikap-tingkah laku
hierarki nilai sikap-tingkah laku
 
Gli zeppelin
Gli zeppelinGli zeppelin
Gli zeppelin
 

More from Zenika

Datascience & IoT
Datascience & IoTDatascience & IoT
Datascience & IoTZenika
 
Matinale Agile Wake Up #4 : les tests et l'agilité
Matinale Agile Wake Up #4 : les tests et l'agilitéMatinale Agile Wake Up #4 : les tests et l'agilité
Matinale Agile Wake Up #4 : les tests et l'agilitéZenika
 
Agile Wake Up #3 : Lean UX
Agile Wake Up #3 : Lean UXAgile Wake Up #3 : Lean UX
Agile Wake Up #3 : Lean UXZenika
 
Agile Wake Up #3 : La transformation Agile de Kisio Digital
Agile Wake Up #3 : La transformation Agile de Kisio DigitalAgile Wake Up #3 : La transformation Agile de Kisio Digital
Agile Wake Up #3 : La transformation Agile de Kisio DigitalZenika
 
Agile Wake Up #3 : la contractualisation Agile
Agile Wake Up #3 : la contractualisation AgileAgile Wake Up #3 : la contractualisation Agile
Agile Wake Up #3 : la contractualisation AgileZenika
 
Zenika matinale spark-zeppelin_ml
Zenika matinale spark-zeppelin_mlZenika matinale spark-zeppelin_ml
Zenika matinale spark-zeppelin_mlZenika
 
Docker du mythe à la réalité
Docker du mythe à la réalitéDocker du mythe à la réalité
Docker du mythe à la réalitéZenika
 
Motivation 3.0 : sens, autonomie et maîtrise.
Motivation 3.0 : sens, autonomie et maîtrise.Motivation 3.0 : sens, autonomie et maîtrise.
Motivation 3.0 : sens, autonomie et maîtrise.Zenika
 
Matinale React
Matinale ReactMatinale React
Matinale ReactZenika
 
NigthClazz Spark - Machine Learning / Introduction à Spark et Zeppelin
NigthClazz Spark - Machine Learning / Introduction à Spark et ZeppelinNigthClazz Spark - Machine Learning / Introduction à Spark et Zeppelin
NigthClazz Spark - Machine Learning / Introduction à Spark et ZeppelinZenika
 
NightClazz Spark / Machine Learning
NightClazz Spark / Machine LearningNightClazz Spark / Machine Learning
NightClazz Spark / Machine LearningZenika
 
HTTP2 : ce qui va changer par Julien Landuré
HTTP2 : ce qui va changer par Julien LanduréHTTP2 : ce qui va changer par Julien Landuré
HTTP2 : ce qui va changer par Julien LanduréZenika
 
Agile Wake Up #1 du 01/12/2015 : L'agilité au service des projets Orange Fran...
Agile Wake Up #1 du 01/12/2015 : L'agilité au service des projets Orange Fran...Agile Wake Up #1 du 01/12/2015 : L'agilité au service des projets Orange Fran...
Agile Wake Up #1 du 01/12/2015 : L'agilité au service des projets Orange Fran...Zenika
 
Agile Wake Up #1 du 01/12/2015 : Scrum Master's Diary par Arnaud Villenave
Agile Wake Up #1 du 01/12/2015 : Scrum Master's Diary par Arnaud VillenaveAgile Wake Up #1 du 01/12/2015 : Scrum Master's Diary par Arnaud Villenave
Agile Wake Up #1 du 01/12/2015 : Scrum Master's Diary par Arnaud VillenaveZenika
 
Agile Wake Up #1 du 01/12/2015 : L'agilité à grande échelle
Agile Wake Up #1 du 01/12/2015 : L'agilité à grande échelleAgile Wake Up #1 du 01/12/2015 : L'agilité à grande échelle
Agile Wake Up #1 du 01/12/2015 : L'agilité à grande échelleZenika
 
Entreprise libérée : Du mythe à la réalité ?
Entreprise libérée : Du mythe à la réalité ?Entreprise libérée : Du mythe à la réalité ?
Entreprise libérée : Du mythe à la réalité ?Zenika
 
Conference MicroServices101 - 1ere partie
Conference MicroServices101 - 1ere partieConference MicroServices101 - 1ere partie
Conference MicroServices101 - 1ere partieZenika
 
NightClazz Docker Découverte
NightClazz Docker Découverte NightClazz Docker Découverte
NightClazz Docker Découverte Zenika
 
Matinale DevOps / Docker
Matinale DevOps / DockerMatinale DevOps / Docker
Matinale DevOps / DockerZenika
 
NightClazz Java 8 Decouverte
NightClazz Java 8 DecouverteNightClazz Java 8 Decouverte
NightClazz Java 8 DecouverteZenika
 

More from Zenika (20)

Datascience & IoT
Datascience & IoTDatascience & IoT
Datascience & IoT
 
Matinale Agile Wake Up #4 : les tests et l'agilité
Matinale Agile Wake Up #4 : les tests et l'agilitéMatinale Agile Wake Up #4 : les tests et l'agilité
Matinale Agile Wake Up #4 : les tests et l'agilité
 
Agile Wake Up #3 : Lean UX
Agile Wake Up #3 : Lean UXAgile Wake Up #3 : Lean UX
Agile Wake Up #3 : Lean UX
 
Agile Wake Up #3 : La transformation Agile de Kisio Digital
Agile Wake Up #3 : La transformation Agile de Kisio DigitalAgile Wake Up #3 : La transformation Agile de Kisio Digital
Agile Wake Up #3 : La transformation Agile de Kisio Digital
 
Agile Wake Up #3 : la contractualisation Agile
Agile Wake Up #3 : la contractualisation AgileAgile Wake Up #3 : la contractualisation Agile
Agile Wake Up #3 : la contractualisation Agile
 
Zenika matinale spark-zeppelin_ml
Zenika matinale spark-zeppelin_mlZenika matinale spark-zeppelin_ml
Zenika matinale spark-zeppelin_ml
 
Docker du mythe à la réalité
Docker du mythe à la réalitéDocker du mythe à la réalité
Docker du mythe à la réalité
 
Motivation 3.0 : sens, autonomie et maîtrise.
Motivation 3.0 : sens, autonomie et maîtrise.Motivation 3.0 : sens, autonomie et maîtrise.
Motivation 3.0 : sens, autonomie et maîtrise.
 
Matinale React
Matinale ReactMatinale React
Matinale React
 
NigthClazz Spark - Machine Learning / Introduction à Spark et Zeppelin
NigthClazz Spark - Machine Learning / Introduction à Spark et ZeppelinNigthClazz Spark - Machine Learning / Introduction à Spark et Zeppelin
NigthClazz Spark - Machine Learning / Introduction à Spark et Zeppelin
 
NightClazz Spark / Machine Learning
NightClazz Spark / Machine LearningNightClazz Spark / Machine Learning
NightClazz Spark / Machine Learning
 
HTTP2 : ce qui va changer par Julien Landuré
HTTP2 : ce qui va changer par Julien LanduréHTTP2 : ce qui va changer par Julien Landuré
HTTP2 : ce qui va changer par Julien Landuré
 
Agile Wake Up #1 du 01/12/2015 : L'agilité au service des projets Orange Fran...
Agile Wake Up #1 du 01/12/2015 : L'agilité au service des projets Orange Fran...Agile Wake Up #1 du 01/12/2015 : L'agilité au service des projets Orange Fran...
Agile Wake Up #1 du 01/12/2015 : L'agilité au service des projets Orange Fran...
 
Agile Wake Up #1 du 01/12/2015 : Scrum Master's Diary par Arnaud Villenave
Agile Wake Up #1 du 01/12/2015 : Scrum Master's Diary par Arnaud VillenaveAgile Wake Up #1 du 01/12/2015 : Scrum Master's Diary par Arnaud Villenave
Agile Wake Up #1 du 01/12/2015 : Scrum Master's Diary par Arnaud Villenave
 
Agile Wake Up #1 du 01/12/2015 : L'agilité à grande échelle
Agile Wake Up #1 du 01/12/2015 : L'agilité à grande échelleAgile Wake Up #1 du 01/12/2015 : L'agilité à grande échelle
Agile Wake Up #1 du 01/12/2015 : L'agilité à grande échelle
 
Entreprise libérée : Du mythe à la réalité ?
Entreprise libérée : Du mythe à la réalité ?Entreprise libérée : Du mythe à la réalité ?
Entreprise libérée : Du mythe à la réalité ?
 
Conference MicroServices101 - 1ere partie
Conference MicroServices101 - 1ere partieConference MicroServices101 - 1ere partie
Conference MicroServices101 - 1ere partie
 
NightClazz Docker Découverte
NightClazz Docker Découverte NightClazz Docker Découverte
NightClazz Docker Découverte
 
Matinale DevOps / Docker
Matinale DevOps / DockerMatinale DevOps / Docker
Matinale DevOps / Docker
 
NightClazz Java 8 Decouverte
NightClazz Java 8 DecouverteNightClazz Java 8 Decouverte
NightClazz Java 8 Decouverte
 

Recently uploaded

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 

Recently uploaded (20)

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 

Deadlock Victim

  • 1. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Deadlock Victim by Dr Heinz Kabutz && Olivier Croisier The Java Specialists Newsletter && The Coder's Breakfast heinz@javaspecialists.eu && olivier.croisier@zenika.com twitter: @heinzkabutz && twitter: @oliviercroisier 1
  • 2. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr You discover a race condition 2
  • 3. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Data is being corrupted 3
  • 4. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr What ya gonna do? 4
  • 5. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Who ya gonna call? 5
  • 6. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Ghostbusters? 6
  • 7. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr you do what we all do 7
  • 8. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr you use synchronized 8
  • 9. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr synchronized 9
  • 10. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr synchronized 9
  • 11. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr synchronized can be bad medicine 10
  • 12. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr deadlock awaits you! 11
  • 13. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr 12
  • 14. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Deadlock Victim 13
  • 15. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Correctness fix can lead to liveness fault 14
  • 16. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr lock ordering deadlock 15
  • 17. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr at least two locks 16
  • 18. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr and at least two threads 17
  • 19. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr locked in different orders 18
  • 20. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr can cause a deadly embrace 19
  • 21. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr requires global analysis to fix 20
  • 22. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr resource deadlocks 21
  • 23. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr bounded queues 22
  • 24. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr bounded thread pools 23
  • 25. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr semaphores 24
  • 26. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr class loaders 25
  • 27. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr lost signals 26
  • 28. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr The Drinking Philosophers 27
  • 29. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr @ the Java Specialist Symposium in Crete 28
  • 30. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Symposium == sym + poto Literally - to drink together 29
  • 31. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr our philosophers need two cups 30
  • 32. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr they either want to drink or think 31
  • 33. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Table is ready, all philosophers are thinking 1 5 2 4 3 32
  • 34. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr philosophers 5 wants to drink, takes right cup 1 5 2 4 3 33
  • 35. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Philosopher 5 is now drinking with both cups 1 5 2 4 3 34
  • 36. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr philosophers 3 wants to drink, takes right cup 1 5 2 4 3 35
  • 37. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Philosopher 3 is now drinking with both cups 1 5 2 4 3 36
  • 38. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr philosophers 2 wants to drink, takes right cup 1 5 2 4 3 37
  • 39. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Philosopher 3 finished drinking, returns right cup 1 5 2 4 3 38
  • 40. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Philosopher 2 is now drinking with both cups 1 5 2 4 3 39
  • 41. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Philosopher 3 returns Left cup 1 5 2 4 3 40
  • 42. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr philosophers can get stuck 41
  • 43. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr if they all pick up the right cup 42
  • 44. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr A deadlock can easily happen with this design 1 5 2 4 3 43
  • 45. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Philosopher 5 wants to drink, takes right cup 1 5 2 4 3 44
  • 46. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Philosopher 1 wants to drink, takes right cup 1 5 2 4 3 45
  • 47. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Philosopher 2 wants to drink, takes right cup 1 5 2 4 3 46
  • 48. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Philosopher 3 wants to drink, takes right cup 1 5 2 4 3 47
  • 49. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Philosopher 4 wants to drink, takes right cup 1 5 2 4 3 48
  • 50. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Deadlock! 1 5 2 4 3 49
  • 51. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr they will all stay thirsty 1 5 2 4 3 50
  • 52. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr this is a deadly embrace 1 5 2 4 3 51
  • 53. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr this can be detected automatically 52
  • 54. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr search the graph of call stacks 53
  • 55. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr and look for circular dependencies 54
  • 56. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr ThreadMXBean does that for us 55
  • 57. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr simple deadlocks are quickly found 56
  • 58. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr but what do you DO with them? 57
  • 59. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr what will the dog do with the car if he ever catches it? 58
  • 60. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr databases choose deadlock victim 59
  • 61. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr but what does Java do? 60
  • 62. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr it should probably throw an Error 61
  • 63. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr but the threads simply hang up 62
  • 64. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr it is best to avoid causing them! 63
  • 65. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr global order of locks in program 64
  • 66. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr public class LeftRightDeadlock { private final Object left = new Object(); private final Object right = new Object(); public void leftRight() { synchronized (left) { synchronized (right) { doSomething(); } } } public void rightLeft() { synchronized (right) { synchronized (left) { doSomethingElse(); } } } } 65
  • 67. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Interleaving causes deadlock lock left trying to lock right A leftRight() BLOCKED lock right trying to lock left B rightLeft() BLOCKED 66
  • 68. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr we define a fixed global order 67
  • 69. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr e.g. left before right 68
  • 70. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr deadlock is solved! public void rightLeft() { synchronized (left) { synchronized (right) { doSomethingElse(); } } } 69
  • 71. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr our drinking philosophers 70
  • 72. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr each cup gets a unique number 71
  • 73. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr lock the highest number cup first 72
  • 74. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr then lock the lower number cup 73
  • 75. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr drink 74
  • 76. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr unlock lower order cup 75
  • 77. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr unlock higher order cup 76
  • 78. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr think 77
  • 79. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Global Lock ordering • We start with all the 1 philosophers thinking 1 2 5 2 5 3 4 4 3 78
  • 80. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Philosopher 5 takes cup 5 • Cup 5 has higher number 1 • Remember our rule! 1 2 5 2 5 3 4 4 3 79
  • 81. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Philosopher 1 takes cup 2 • Must take the cup with 1 the higher number 2 first 1 • In this case 5 2 cup 2 5 3 4 4 3 80
  • 82. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Philosopher 2 takes cup 3 1 2 1 5 2 5 3 4 4 3 81
  • 83. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Philosopher 3 takes cup 4 1 2 1 5 2 5 3 4 4 3 82
  • 84. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Philosopher 1 takes cup 1 - Drinking 1 1 2 5 2 5 3 4 4 3 83
  • 85. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Philosopher 1 returns Cup 1 • Cups are returned in the 1 opposite order to what 2 they are acquired 1 5 2 5 3 4 4 3 84
  • 86. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Philosopher 5 takes cup 1 - Drinking 1 2 1 5 2 5 3 4 4 3 85
  • 87. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Philosopher 5 returns cup 1 1 2 1 5 2 5 3 4 4 3 86
  • 88. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Philosopher 1 returns cup 2 1 1 2 5 2 5 3 4 4 3 87
  • 89. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Philosopher 2 takes cup 2 - Drinking 1 2 1 5 2 5 3 4 4 3 88
  • 90. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Philosopher 5 returns cup 5 1 2 1 5 2 3 5 4 4 3 89
  • 91. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Philosopher 4 takes cup 5 1 2 1 5 2 3 5 4 4 3 90
  • 92. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Philosopher 2 returns cup 2 1 1 2 5 2 3 5 4 4 3 91
  • 93. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Philosopher 2 returns cup 3 1 1 2 5 2 3 5 4 4 3 92
  • 94. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Philosopher 3 takes cup 3 - Drinking 1 1 2 5 2 5 3 4 4 3 93
  • 95. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Philosopher 3 Returns cup 3 1 1 2 5 2 3 5 4 4 3 94
  • 96. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Philosopher 3 Returns cup 4 1 1 2 5 2 3 5 4 4 3 95
  • 97. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Philosopher 4 takes cup 4 - Drinking 1 1 2 5 2 3 5 4 4 3 96
  • 98. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Philosopher 4 Returns cup 4 1 1 2 5 2 3 5 4 4 3 97
  • 99. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Philosopher 4 Returns cup 5 1 1 2 5 2 5 3 4 4 3 98
  • 100. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr sorting locks by property is easy 99
  • 101. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr e.g. account IBAN number 100
  • 102. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr or employee number 101
  • 103. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr or some other characteristic 102
  • 104. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr maybe even System.identityHashCode() 103
  • 105. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr use "open calls" 104
  • 106. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Vector synchronizes writeObject() private synchronized void writeObject(ObjectOutputStream s) throws IOException { s.defaultWriteObject(); } 105
  • 107. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr synchronized writeObject() is invoking s.defaultWriteObject() private synchronized void writeObject(ObjectOutputStream s) throws IOException { s.defaultWriteObject(); } 106
  • 108. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr this is not an "open call" private synchronized void writeObject(ObjectOutputStream s) throws IOException { s.defaultWriteObject(); } 107
  • 109. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr but can it cause problems? private synchronized void writeObject(ObjectOutputStream s) throws IOException { s.defaultWriteObject(); } 108
  • 110. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr yes it can! private synchronized void writeObject(ObjectOutputStream s) throws IOException { s.defaultWriteObject(); } 109
  • 111. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr serialize both vectors at same time Vector v1 = new Vector(); Vector v2 = new Vector(); v1.add(v2); v2.add(v1); 110
  • 112. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr this could happen with nested data structures 111
  • 113. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr it happened to an IBM client 112
  • 114. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr private void writeObject(ObjectOutputStream stream) throws IOException { Vector<E> cloned = null; // this specially fix is for a special dead-lock in customer // program: two vectors refer each other may meet dead-lock in // synchronized serialization. Refer CMVC-103316.1 synchronized (this) { try { cloned = (Vector<E>) super.clone(); cloned.elementData = elementData.clone(); } catch (CloneNotSupportedException e) { // no deep clone, ignore the exception } } cloned.writeObjectImpl(stream); } private void writeObjectImpl(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); } 113
  • 115. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Java 7 uses an "open call" private void writeObject(ObjectOutputStream s) throws IOException { final ObjectOutputStream.PutField fields = s.putFields(); final Object[] data; synchronized (this) { fields.put("capacityIncrement", capacityIncrement); fields.put("elementCount", elementCount); data = elementData.clone(); } fields.put("elementData", data); s.writeFields(); } 114
  • 116. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr More synchronized writeObject()s • File • StringBuffer • Throwable • URL • Hashtable • and others 115
  • 117. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr we have seen the deadly embrace 116
  • 118. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr are there other deadlocks? 117
  • 119. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr semaphore deadlocks 118
  • 120. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Bounded DB Connection Pools • For example, say you have two DB connection pools • Some tasks might require connections to both databases • Thus thread A might hold semaphore for D1 and wait for D2, whereas thread B might hold semaphore for D2 and be waiting for D1 119
  • 121. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr public class DatabasePool { private final Semaphore connections; public DatabasePool(int connections) { this.connections = new Semaphore(connections); } public void connect() { connections.acquireUninterruptibly(); System.out.println("DatabasePool.connect"); } public void disconnect() { System.out.println("DatabasePool.disconnect"); connections.release(); } } 120
  • 122. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr ThreadMXBean does not show this as a deadlock! 121
  • 123. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr JVM does not detect this deadlock 122
  • 124. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr JVM does not detect this deadlock 122
  • 125. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Avoiding and diagnosing deadlocks Avoiding Liveness Hazards 123
  • 126. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Avoiding and diagnosing deadlocks • You cannot get a lock-ordering deadlock with a single lock • Easiest way to avoid deadlocks • But not always practical 124
  • 127. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Avoiding and diagnosing deadlocks • For multiple locks we need to define a lock order • specify and document possible lock sequences • Identify where multiple locks could be acquired • Do a global analysis to ensure that lock ordering is consistent • This can be extremely difficult in large programs 125
  • 128. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Use open calls whenever possible 126
  • 129. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Unit Testing for lock ordering deadlocks • Code typically has to be called many times before a deadlock happens • How many times do you need to call it to prove that there is no deadlock? • Nondeterministic unit tests are bad - they should either always pass or always fail 127
  • 130. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Testing the Bank • In the transferMoney() method, a deadlock occurs if after the first lock is granted, the first thread is swapped out and another thread requests the second lock public class Bank { public boolean transferMoney(Account from, Account to, Amount amount) { synchronized (from) { // if thread is swapped out here, we can end up with a deadlock synchronized (to) { return doActualTransfer(from, to, amount); } } } } 128
  • 131. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr We can force the context switch 129
  • 132. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr simply add a sleep after first lock 130
  • 133. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Adding a sleep to cause deadlocks public class Bank { public boolean transferMoney(Account from, Account to, Amount amount) { synchronized (from) { sleepAWhileForTesting(); synchronized (to) { return doActualTransfer(from, to, amount); } } } protected void sleepAWhileForTesting() {} } 131
  • 134. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr In our unit test we use a SlowBank public class SlowBank extends Bank { private final long timeout; private final TimeUnit unit; public SlowBank(long timeout, TimeUnit unit) { this.timeout = timeout; this.unit = unit; } protected void sleepAWhileForTesting() { try { unit.sleep(timeout); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } 132
  • 135. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Won't this cause problems in production? 133
  • 136. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr In production we only use Bank 134
  • 137. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr HotSpot will optimize away empty sleepAWhileForTesting() 135
  • 138. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr it is thus a zero cost 136
  • 139. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr as long as SlowBank is never used 137
  • 140. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr How can you verify the lock- ordering deadlock? 138
  • 141. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr CTRL+Break, jstack, kill -3, jconsole, etc. 139
  • 142. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr but that won't be a good unit test 140
  • 143. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Better via Java's ThreadMXBean 141
  • 144. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr ThreadMXBean • Get instance with ManagementFactory.getThreadMXBean() • findMonitorDeadlockedThreads() • Includes only "monitor" locks, i.e. synchronized • Only way to find deadlocks in Java 5 142
  • 145. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr ThreadMXBean • Better is findDeadlockedThreads() • Includes "monitor" and "owned" (Java 5) locks • Preferred method to test for deadlocks • But, does not find deadlocks between semaphores • See http://www.javaspecialists.eu/archive/Issue130.html 143
  • 146. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr public class BankDeadlockTest { private final static ThreadMXBean tmb = ManagementFactory.getThreadMXBean(); private boolean isThreadDeadlocked(long tid) { long[] ids = tmb.findDeadlockedThreads(); if (ids == null) return false; for (long id : ids) { if (id == tid) return true; } return false; } 144
  • 147. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr private void checkThatThreadTerminates(Thread thread) throws InterruptedException { for (int i = 0; i < 2000; i++) { thread.join(50); if (!thread.isAlive()) return; if (isThreadDeadlocked(thread.getId())) { fail("Deadlock detected!"); } } fail(thread + " did not terminate in time"); } 145
  • 148. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr @Test public void testForTransferDeadlock() throws InterruptedException { final Account alpha = new Account(new Amount(1000)); final Account ubs = new Account(new Amount(1000000)); final Bank bank = new SlowBank(100, TimeUnit.MILLISECONDS); Thread alphaToUbs = new Thread("alphaToUbs") { public void run() { bank.transferMoney(alpha, ubs, new Amount(100)); } }; Thread ubsToAlpha = new Thread("ubsToAlpha") { public void run() { bank.transferMoney(ubs, alpha, new Amount(100)); } }; alphaToUbs.start(); ubsToAlpha.start(); checkThatThreadTerminates(alphaToUbs); } } 146
  • 149. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Output with broken transferMoney() method • We see the deadlock within about 100 milliseconds junit.framework.AssertionFailedError: Deadlock detected! at BankDeadlockTest.checkThatThreadTerminates(BankDeadlockTest.java:20) at BankDeadlockTest.testForTransferDeadlock(BankDeadlockTest.java:55) 147
  • 150. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Output with broken transferMoney() method • If we fix the transferMoney() method, it also completes within about 100 milliseconds • This is the time that we are sleeping for testing purposes • Remember that the empty sleepAWhileForTesting() method will be optimized away by HotSpot 148
  • 151. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Timed lock attempts • Another technique for solving deadlocks is to use the timed tryLock() method of explicit Java locks 149
  • 152. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr However, if tryLock() fails it may be 150
  • 153. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr a deadlock 151
  • 154. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr or some thread taking a long time 152
  • 155. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr or a thread in an infinite loop 153
  • 156. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr But ThreadMXBean shows it as deadlocked 154
  • 157. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr even if it is a temporary condition 155
  • 158. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr The JVM has support for tryLock with synchronized 156
  • 159. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr but it is hidden away 157
  • 160. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr So here it is 158
  • 161. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr 159
  • 162. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Told you it was hidden! 160
  • 163. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr It is hidden for a good reason 161
  • 164. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr if you need tryLock functionality 162
  • 165. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr rather use explicit locks (ReentrantLock) 163
  • 166. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr tryLock with synchronized • Technically possible in Sun JVM using • Unsafe.getUnsafe().tryMonitorEnter(monitor) • Unsafe.getUnsafe().monitorExit(monitor) • http://www.javaspecialists.eu/archive/Issue194.html 164
  • 167. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Deadlock analysis with thread dumps 165
  • 168. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Deadlock analysis with thread dumps • We can also cause a thread dump in many ways: • Ctrl+Break on Windows or Ctrl- on Unix • Invoking "kill -3" on the process id • Calling jstack on the process id • Only shows deadlocks since Java 6 • Intrinsic locks show more information of where they were acquired 166
  • 169. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Can a deadlock be resolved? 167
  • 170. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr NO with synchronized 168
  • 171. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr YES with ReentrantLock 169
  • 172. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr synchronized() goes into BLOCKED state 170
  • 173. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr ReentrantLock.lock() goes into WAITING state 171
  • 174. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr We can write a DealockArbitrator 172
  • 175. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr This stops one of the threads with a DeadlockVictimError 173
  • 176. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Our special Error for deadlocks public class DeadlockVictimError extends Error { private final Thread victim; public DeadlockVictimError(Thread victim) { super("Deadlock victim: " + victim); this.victim = victim; } public Thread getVictim() { return victim; } } 174
  • 177. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr public class DeadlockArbitrator { private static final ThreadMXBean tmb = ManagementFactory.getThreadMXBean(); public boolean tryResolveDeadlock( int attempts, long timeout, TimeUnit unit) throws InterruptedException { for (int i = 0; i < attempts; i++) { long[] ids = tmb.findDeadlockedThreads(); if (ids == null) return true; Thread t = findThread(ids[i % ids.length]); if (t == null) throw new IllegalStateException("Could not find thread"); t.stop(new DeadlockVictimError(t)); unit.sleep(timeout); } return false; } 175
  • 178. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr finding threads by id is tricky public boolean tryResolveDeadlock() throws InterruptedException { return tryResolveDeadlock(3, 1, TimeUnit.SECONDS); } private Thread findThread(long id) { for (Thread thread : Thread.getAllStackTraces().keySet()) { if (thread.getId() == id) return thread; } return null; } } 176
  • 179. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Applicability of DeadlockArbitrator • Only use in extreme circumstances • Code that is outside your control and that deadlocks • Where you cannot prevent the deadlock • Remember, it only works with ReentrantLock 177
  • 180. The Java Specialists' Newsletter - javaspecialists.eu / zenika.fr Deadlock Victim Questions? by Dr Heinz Kabutz && Olivier Croisier The Java Specialists Newsletter && The Coder's Breakfast heinz@javaspecialists.eu && olivier.croisier@zenika.com twitter: @heinzkabutz && twitter: @oliviercroisier 178