Deadlocks happen when two or more threads are blocked forever because each has acquired a resource and waits for another resource which is already taken by another thread. They are usually nasty and unpredictable, but it’s possible to make them fun. Try to create a guaranteed deadlock using only standard Java libraries (Maven/Gradle import of third party deadlock libraries should not be used).

When you think of deadlock, the first code you might imagine is:

public class Deadlock1 implements Runnable {
 private final Object o1;
 private final Object o2;

 private Deadlock1(String s1, String s2) {
  o1 = s1.intern();
  o2 = s2.intern();
 }

 public static void main(String[] args) {
   new Thread(new Deadlock1("a", "b")).start();
   new Thread(new Deadlock1("b", "a")).start();
 }

 @Override
 public void run() {
   synchronized (o1) {
     try {
       Thread.sleep(5000);
     } catch (InterruptedException e) {
       e.printStackTrace();
     }
     synchronized (o2) {
     }
   }
 }
}

Using delays to make sure some event happens is widely used in tests. This code will likely cause a deadlock in JRE but it is not guaranteed – any thread may finish by the time another one starts.

Another attempt may look like:

import java.util.Random;

public class Deadlock2 implements Runnable {
 private final Object o1;
 private final Object o2;
 private Deadlock2(Object o1, Object o2) {
   this.o1 = o1;
   this.o2 = o2;
 }

 public static void main(String[] args) {
   new Thread(new Deadlock2(Object.class, String.class)).start();
   new Thread(new Deadlock2(Object.class, String.class)).start();
 }

 @Override
 public void run() {
   Random rnd = new Random();
   while (true) {
     synchronized (rnd.nextBoolean() ? o1 : o2) {
       synchronized (rnd.nextBoolean() ? o1 : o2) {
       }
     }
   }
 }
}

It will likely cause a deadlock, too. Using randomization in code in an attempt to use different resources is even more popular than using delays but it’s still not guaranteed – what if one of threads always grabs the same object?

So making a guaranteed deadlock that doesn’t rely on randomization and delays is tricky. You’ll definitely have a deeper knowledge of concurrency and synchronization in Java when you complete this exercise.

Next step for deadlock fun is challenge with your teammates – who will create the shortest code. You’ll see many tricks you haven’t thought of and will be reading docs in depth trying to find a fault in peer’s code and prove correctness of yours, which, again, will take your knowledge of multi-threading programming in Java to the next level. Beware: if you announce this challenge during release time, schedule delays may happen.

Leave a comment

Your email address will not be published. Required fields are marked *