How to write deadlock in Java

An example of deadlock in Java:

class Ruller {
  private static final Ruller RULLER = new Ruller();
  private Ruller() {}
  public static Ruller getInstance() { return RULLER; }
  public synchronized void ruller() {
    System.out.println("RULLER:" + currentThread());

class Pen {
  public static synchronized void pen() {
    System.out.println("PEN:" + currentThread());
    try { Thread.sleep(50); }
    catch(InterruptedException e){e.printStackTrace();}

public class DeadlockExample {
  public static void main(String[] args) {
    new Thread(new Runnable() {
      public void run() {

The output is (or opposite order):


Is this case, first thread-0 (created and started programmatically) enters synchronized pen() method and sleeps 50 ms. While sleeping main thread enters synchronized ruller() method and immediately tries to access pen() method which has monitor locked on class Pen by thread-0. After tread-0 finishes sleeping it tries to access ruller() method which is locked on singleton instance of Ruller class. Both methods are waiting for each other to proceed and application hangs.

Thread dump created by command jstack pid produces the following (or for Tomcat kill -3 pid; output in catalina.out) :

"Thread-0" prio=10 tid=0x09535000 nid=0x4013 waiting for monitor entry [0x802fb000]
  java.lang.Thread.State: BLOCKED (on object monitor) at
  - waiting to lock (a deadlock.Ruller) at
  - locked (a java.lang.Class for deadlock.Pen) at  deadlock.DeadlockExample$
"main" prio=10 tid=0x09485800 nid=0x4004 waiting for monitor entry [0xb69a3000]
  java.lang.Thread.State: BLOCKED (on object monitor) at
  - waiting to lock (a java.lang.Class for deadlock.Pen)
  at deadlock.Ruller.ruller(
  - locked (a deadlock.Ruller) at
Found one Java-level deadlock:
  waiting to lock monitor 0x09507560 (object 0xa3ee89d0, a deadlock.Ruller),
  which is held by "main"
  waiting to lock monitor 0x095068e0 (object 0x80da7aa8, a java.lang.Class),
  which is held by "Thread-0"


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s