Deadlocks

A deadlock occurs when two or more threads stop execution waiting on each other or a shared resource. While race conditions happen generally through a deficiency of locking, deadlocks occur through incorrect or overzealous locking. Listing 13-4 shows two methods that are destined to eventually deadlock.

Listing 13-4: Two methods likely to deadlock if running on the same object in different threads at the same time

public class ClassA {  private ClassB that;  public void doSomething() {    synchronized(this) {      synchronized(that) {        // Do the work      }    }  }  public void doSomethingElse() {    synchronized(that) {      synchronized(this) {        // Do other work      }    }  }}

Note the opposite ...

Get Quality Code: Software Testing Principles, Practices, and Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.