Java Deadlock Example and How to analyze deadlock situation

source:http://www.journaldev.com/1058/java-deadlock-example-and-how-to-analyze-deadlock-situation

Deadlock is a programming situation where two or more threads are blocked forever, this situation arises with at least two threads and two or more resources. Here I have written a simple program that will cause deadlock scenario and then we will see how to analyze it.

Java Deadlock Example

ThreadDeadlock.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

package com.journaldev.threads;

public class ThreadDeadlock {

    public static void main(String[] args) throws InterruptedException {

        Object obj1 = new Object();

        Object obj2 = new Object();

        Object obj3 = new Object();

    

        Thread t1 = new Thread(new SyncThread(obj1, obj2), "t1");

        Thread t2 = new Thread(new SyncThread(obj2, obj3), "t2");

        Thread t3 = new Thread(new SyncThread(obj3, obj1), "t3");

        

        t1.start();

        Thread.sleep(5000);

        t2.start();

        Thread.sleep(5000);

        t3.start();

        

    }

}

class SyncThread implements Runnable{

    private Object obj1;

    private Object obj2;

    public SyncThread(Object o1, Object o2){

        this.obj1=o1;

        this.obj2=o2;

    }

    @Override

    public void run() {

        String name = Thread.currentThread().getName();

        System.out.println(name + " acquiring lock on "+obj1);

        synchronized (obj1) {

         System.out.println(name + " acquired lock on "+obj1);

         work();

         System.out.println(name + " acquiring lock on "+obj2);

         synchronized (obj2) {

            System.out.println(name + " acquired lock on "+obj2);

            work();

        }

         System.out.println(name + " released lock on "+obj2);

        }

        System.out.println(name + " released lock on "+obj1);

        System.out.println(name + " finished execution.");

    }

    private void work() {

        try {

            Thread.sleep(30000);

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

    }

}

In above program SyncThread is implementing Runnable interface and it works on two Objects by acquiring lock on each one of them one by one using synchronized block.

In main method, I have three threads running for SyncThread and there is a shared resource between each of the threads. The threads are run in such a way that it will be able to acquire lock on the first object but when it’s trying to acquire lock on second object, it goes on wait state because it’s already locked by another thread. This forms a cyclic dependency for resource between Threads causing deadlock.

When I execute the above program, here is the output generated but program never terminates because of deadlock.


1

2

3

4

5

6

7

8

9

t1 acquiring lock on [email protected]

t1 acquired lock on [email protected]

t2 acquiring lock on [email protected]

t2 acquired lock on [email protected]

t3 acquiring lock on [email protected]

t3 acquired lock on [email protected]

t1 acquiring lock on [email protected]

t2 acquiring lock on [email protected]

t3 acquiring lock on [email protected]

Here we can clearly identify the deadlock situation from the output but in real life applications it’s very hard to find the deadlock situation and debug them.

Analyze Deadlock

To analyze a deadlock, we need to look at the java thread dump of the application, in last post I explained how we can generate thread dump using VisualVM profiler or using jstack utility.

Here is the thread dump of above program.

2012-12-27 19:08:34

Full thread dump Java HotSpot(TM) 64-Bit Server VM (23.5-b02 mixed mode):

"Attach Listener" daemon prio=5 tid=0x00007fb0a2814000 nid=0x4007 waiting on condition [0x0000000000000000]

   java.lang.Thread.State: RUNNABLE

"DestroyJavaVM" prio=5 tid=0x00007fb0a2801000 nid=0x1703 waiting on condition [0x0000000000000000]

   java.lang.Thread.State: RUNNABLE

"t3" prio=5 tid=0x00007fb0a204b000 nid=0x4d07 waiting for monitor entry [0x000000015d971000]

   java.lang.Thread.State: BLOCKED (on object monitor)

    at com.journaldev.threads.SyncThread.run(ThreadDeadlock.java:41)

    - waiting to lock <0x000000013df2f658> (a java.lang.Object)

    - locked <0x000000013df2f678> (a java.lang.Object)

    at java.lang.Thread.run(Thread.java:722)

"t2" prio=5 tid=0x00007fb0a1073000 nid=0x4207 waiting for monitor entry [0x000000015d209000]

   java.lang.Thread.State: BLOCKED (on object monitor)

    at com.journaldev.threads.SyncThread.run(ThreadDeadlock.java:41)

    - waiting to lock <0x000000013df2f678> (a java.lang.Object)

    - locked <0x000000013df2f668> (a java.lang.Object)

    at java.lang.Thread.run(Thread.java:722)

"t1" prio=5 tid=0x00007fb0a1072000 nid=0x5503 waiting for monitor entry [0x000000015d86e000]

   java.lang.Thread.State: BLOCKED (on object monitor)

    at com.journaldev.threads.SyncThread.run(ThreadDeadlock.java:41)

    - waiting to lock <0x000000013df2f668> (a java.lang.Object)

    - locked <0x000000013df2f658> (a java.lang.Object)

    at java.lang.Thread.run(Thread.java:722)

"Service Thread" daemon prio=5 tid=0x00007fb0a1038000 nid=0x5303 runnable [0x0000000000000000]

   java.lang.Thread.State: RUNNABLE

"C2 CompilerThread1" daemon prio=5 tid=0x00007fb0a1037000 nid=0x5203 waiting on condition [0x0000000000000000]

   java.lang.Thread.State: RUNNABLE

"C2 CompilerThread0" daemon prio=5 tid=0x00007fb0a1016000 nid=0x5103 waiting on condition [0x0000000000000000]

   java.lang.Thread.State: RUNNABLE

"Signal Dispatcher" daemon prio=5 tid=0x00007fb0a4003000 nid=0x5003 runnable [0x0000000000000000]

   java.lang.Thread.State: RUNNABLE

"Finalizer" daemon prio=5 tid=0x00007fb0a4800000 nid=0x3f03 in Object.wait() [0x000000015d0c0000]

   java.lang.Thread.State: WAITING (on object monitor)

    at java.lang.Object.wait(Native Method)

    - waiting on <0x000000013de75798> (a java.lang.ref.ReferenceQueue$Lock)

    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:135)

    - locked <0x000000013de75798> (a java.lang.ref.ReferenceQueue$Lock)

    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:151)

    at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:177)

"Reference Handler" daemon prio=5 tid=0x00007fb0a4002000 nid=0x3e03 in Object.wait() [0x000000015cfbd000]

   java.lang.Thread.State: WAITING (on object monitor)

    at java.lang.Object.wait(Native Method)

    - waiting on <0x000000013de75320> (a java.lang.ref.Reference$Lock)

    at java.lang.Object.wait(Object.java:503)

    at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:133)

    - locked <0x000000013de75320> (a java.lang.ref.Reference$Lock)

"VM Thread" prio=5 tid=0x00007fb0a2049800 nid=0x3d03 runnable

"GC task thread#0 (ParallelGC)" prio=5 tid=0x00007fb0a300d800 nid=0x3503 runnable

"GC task thread#1 (ParallelGC)" prio=5 tid=0x00007fb0a2001800 nid=0x3603 runnable

"GC task thread#2 (ParallelGC)" prio=5 tid=0x00007fb0a2003800 nid=0x3703 runnable

"GC task thread#3 (ParallelGC)" prio=5 tid=0x00007fb0a2004000 nid=0x3803 runnable

"GC task thread#4 (ParallelGC)" prio=5 tid=0x00007fb0a2005000 nid=0x3903 runnable

"GC task thread#5 (ParallelGC)" prio=5 tid=0x00007fb0a2005800 nid=0x3a03 runnable

"GC task thread#6 (ParallelGC)" prio=5 tid=0x00007fb0a2006000 nid=0x3b03 runnable

"GC task thread#7 (ParallelGC)" prio=5 tid=0x00007fb0a2006800 nid=0x3c03 runnable

"VM Periodic Task Thread" prio=5 tid=0x00007fb0a1015000 nid=0x5403 waiting on condition

JNI global references: 114

Found one Java-level deadlock:

=============================

"t3":

  waiting to lock monitor 0x00007fb0a1074b08 (object 0x000000013df2f658, a java.lang.Object),

  which is held by "t1"

"t1":

  waiting to lock monitor 0x00007fb0a1010f08 (object 0x000000013df2f668, a java.lang.Object),

  which is held by "t2"

"t2":

  waiting to lock monitor 0x00007fb0a1012360 (object 0x000000013df2f678, a java.lang.Object),

  which is held by "t3"

Java stack information for the threads listed above:

===================================================

"t3":

    at com.journaldev.threads.SyncThread.run(ThreadDeadlock.java:41)

    - waiting to lock <0x000000013df2f658> (a java.lang.Object)

    - locked <0x000000013df2f678> (a java.lang.Object)

    at java.lang.Thread.run(Thread.java:722)

"t1":

    at com.journaldev.threads.SyncThread.run(ThreadDeadlock.java:41)

    - waiting to lock <0x000000013df2f668> (a java.lang.Object)

    - locked <0x000000013df2f658> (a java.lang.Object)

    at java.lang.Thread.run(Thread.java:722)

"t2":

    at com.journaldev.threads.SyncThread.run(ThreadDeadlock.java:41)

    - waiting to lock <0x000000013df2f678> (a java.lang.Object)

    - locked <0x000000013df2f668> (a java.lang.Object)

    at java.lang.Thread.run(Thread.java:722)

Found 1 deadlock.

The thread dump output clearly shows the deadlock situation and threads and resources involved causing deadlock situation.

For analyzing deadlock, we need to look out for the threads with state as BLOCKED and then the resources it’s waiting to lock, every resource has a unique ID using which we can find which thread is already holding the lock on the object. For example Thread “t3” is waiting to lock 0x000000013df2f658 but it’s already locked by thread “t1”.

Once we analyze the deadlock situation and found out the threads which are causing deadlock, we need to make code changes to avoid deadlock situation.

Avoid deadlock

These are some of the guidelines using which we can avoid most of the deadlock situations.

  • Avoid Nested Locks: This is the most common reason for deadlocks, avoid locking another resource if you already hold one. It’s almost impossible to get deadlock situation if you are working with only one object lock. For example, here is the another implementation of run() method without nested lock and program runs successfully without deadlock situation.


    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    public void run() {

        String name = Thread.currentThread().getName();

        System.out.println(name + " acquiring lock on " + obj1);

        synchronized (obj1) {

            System.out.println(name + " acquired lock on " + obj1);

            work();

        }

        System.out.println(name + " released lock on " + obj1);

        System.out.println(name + " acquiring lock on " + obj2);

        synchronized (obj2) {

            System.out.println(name + " acquired lock on " + obj2);

            work();

        }

        System.out.println(name + " released lock on " + obj2);

        System.out.println(name + " finished execution.");

    }

  • Lock Only What is Required: You should acquire lock only on the resources you have to work on, for example in above program I am locking the complete Object resource but if we are only interested in one of it’s fields, then we should lock only that specific field not complete object.
  • Avoid waiting indefinitely: You can get deadlock if two threads are waiting for each other to finish indefinitely using thread join. If your thread has to wait for another thread to finish, it’s always best to use join with maximum time you want to wait for thread to finish.

If you liked this tutorial, make sure to check out other java thread tutorial.

时间: 2024-08-28 16:03:58

Java Deadlock Example and How to analyze deadlock situation的相关文章

Java线程与多线程教程

本文由 ImportNew - liken 翻译自 Journaldev. Java线程是执行某些任务的轻量级进程.Java通过Thread类提供多线程支持,应用可以创建并发执行的多个线程. 应用中有两类线程——用户线程和守护线程.当启动应用时,main线程是创建的第一个用户线程,我们可以创建多个用户线程和守护线程.当所有用户进程执行完毕时,JVM终止程序. 可以对不同的线程设置不同的属性,但并不保证高优先级的线程在低优先级线程之前执行.线程调度器是操作系统的部分实现,当一个线程启动后,它的执行

Java中的多线程技术全面详解

本文主要从整体上介绍Java中的多线程技术,对于一些重要的基础概念会进行相对详细的介绍,若有叙述不清晰或是不正确的地方,希望大家指出,谢谢大家:) 为什么使用多线程 并发与并行 我们知道,在单核机器上,"多进程"并不是真正的多个进程在同时执行,而是通过CPU时间分片,操作系统快速在进程间切换而模拟出来的多进程.我们通常把这种情况成为并发,也就是多个进程的运行行为是"一并发生"的,但不是同时执行的,因为CPU核数的限制(PC和通用寄存器只有一套,严格来说在同一时刻只能

C3P0 APPARENT DEADLOCK

一,c3p0执行一段时间后报错例如以下 W 07-26_00:58:27 ThreadPoolAsynchronousRunner.java 608 com[email protected]70929ab6 -- APPARENT DEADLOCK!!! Creating emergency threads for unassigned pending tasks! W 07-26_00:58:39 ThreadPoolAsynchronousRunner.java 608 com[email 

log4j deadlock

用了这么久的Log4j这次倒下了,而且官方也还没有给出解决方案. 描述:tomcat 经过一天多时间的访问,出现了hang ,使用 Jstack 查看堆栈后,发现现成 blocked ,主要是 Log4j 的ROOTlock了. "http-nio-2180-exec-9" #35 daemon prio=5 os_prio=0 tid=0x0000000021a8b000 nid=0x12a8 runnable [0x000000002e5ee000] java.lang.Threa

Troubleshooting &quot;Global Enqueue Services Deadlock detected&quot; (Doc ID 1443482.1)

In this Document   Purpose   Troubleshooting Steps   1. TX deadlock in Exclusive(X) mode   2. TX deadlock in Share(S) mode   3. TM deadlock   4. Single resource deadlock for TX , TM or IV   5. LB deadlock   6. Known Issues   7. Further Diagnosis   Re

Java性能提示(全)

http://www.onjava.com/pub/a/onjava/2001/05/30/optimization.htmlComparing the performance of LinkedLists and ArrayLists (and Vectors) (Page last updated May 2001, Added 2001-06-18, Author Jack Shirazi, Publisher OnJava). Tips: ArrayList is faster than

5 Ways to Use Log Data to Analyze System Performance--reference

Recently we looked across some of the most common behaviors that our community of 25,000 users looked for in their logs with a particular focus on web server logs. In fact our research identified the top 15 web server tags and alerts created by our c

Java Service Wrapper配置详解

1 #encoding=UTF-8 2 # Configuration files must begin with a line specifying the encoding 3 # of the the file. 4 5 #******************************************************************** 6 # Wrapper License Properties (Ignored by Community Edition) 7 #*

Java 线程第三版 第六章 高级同步议题 读书笔记

多线程数据同步错误比较难检测,因为通常是与事件的特定发生顺序有关. 一.同步术语 Barrier(屏障) barrier是多个Thread的集合点:所有的Thread都应该到齐在这个barrier之后才能允许它们继续下去. Condition variable(条件变量) 实际上不是变量,而是与某个lock有关联的变量. Event variable(事件变量) 条件变量的另一个名称. Critical section(临界区) 临界区是synchronized方法或者block. Lock(锁