Java线程之如何分析死锁及避免死锁
什么是死锁
java中的死锁是一种编程情况,其中两个或多个线程被永久阻塞,Java死锁情况出现至少两个线程和两个或更多资源。
在这里,我们将写了一个简单的程序,它将导致java死锁场景,然后我们将分析它。
怎么实现死锁
下面我们一起看一个简单的死锁事例,在主线程中每隔5秒钟启动一个线程,每个线程的执行时间是3秒钟
package com.lkf.mulithread;
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();
}
}
}
运行结果:
t1 acquiring lock on java.lang.Object@25d849fd
t1 acquired lock on java.lang.Object@25d849fd
t2 acquiring lock on java.lang.Object@30298d1f
t2 acquired lock on java.lang.Object@30298d1f
t3 acquiring lock on java.lang.Object@11d32fc4
t3 acquired lock on java.lang.Object@11d32fc4
t1 acquiring lock on java.lang.Object@30298d1f
t2 acquiring lock on java.lang.Object@11d32fc4
t3 acquiring lock on java.lang.Object@25d849fd
可以看到每个线程中都能成功获取第一个对象的锁,最终却阻塞在了获取第二个对象,造成了线程之间的互相等待,形成了死锁
怎么排查死锁
我们通过jstack拿到该应用程序死锁的线程转储文件如下(获取线程转储文件方法):
2018-03-31 15:33:34
Full thread dump Java HotSpot(TM) 64-Bit Server VM (25.161-b12 mixed mode):
"RMI TCP Connection(2)-192.168.1.101" #22 daemon prio=9 os_prio=31 tid=0x00007fe2c81cc000 nid=0xa503 runnable [0x000070000ba7c000]
java.lang.Thread.State: RUNNABLE
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
at java.net.SocketInputStream.read(SocketInputStream.java:171)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
at java.io.BufferedInputStream.read(BufferedInputStream.java:265)
- locked <0x0000000797612b30> (a java.io.BufferedInputStream)
at java.io.FilterInputStream.read(FilterInputStream.java:83)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:550)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler$$Lambda$6/556824457.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Locked ownable synchronizers:
- <0x0000000797612c78> (a java.util.concurrent.ThreadPoolExecutor$Worker)
"JMX server connection timeout 21" #21 daemon prio=9 os_prio=31 tid=0x00007fe2c8968800 nid=0xa703 in Object.wait() [0x000070000b97a000]
java.lang.Thread.State: TIMED_WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
at com.sun.jmx.remote.internal.ServerCommunicatorAdmin$Timeout.run(ServerCommunicatorAdmin.java:168)
- locked <0x0000000797600720> (a [I)
at java.lang.Thread.run(Thread.java:748)
Locked ownable synchronizers:
- None
"RMI Scheduler(0)" #20 daemon prio=9 os_prio=31 tid=0x00007fe2c81bc800 nid=0xa903 waiting on condition [0x000070000b877000]
java.lang.Thread.State: TIMED_WAITING (parking)
at sun.misc.Unsafe.park(Native Method)
- parking to wait for <0x0000000797618010> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:2078)
at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:1093)
at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:809)
at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1074)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1134)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Locked ownable synchronizers:
- None
"RMI TCP Connection(1)-192.168.1.101" #19 daemon prio=9 os_prio=31 tid=0x00007fe2c884e000 nid=0x5903 runnable [0x000070000b773000]
java.lang.Thread.State: RUNNABLE
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
at java.net.SocketInputStream.read(SocketInputStream.java:171)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
at java.io.BufferedInputStream.read(BufferedInputStream.java:265)
- locked <0x0000000797600eb8> (a java.io.BufferedInputStream)
at java.io.FilterInputStream.read(FilterInputStream.java:83)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:550)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler$$Lambda$6/556824457.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Locked ownable synchronizers:
- <0x0000000797600ff8> (a java.util.concurrent.ThreadPoolExecutor$Worker)
"RMI TCP Accept-0" #18 daemon prio=9 os_prio=31 tid=0x00007fe2c8855000 nid=0x5703 runnable [0x000070000b671000]
java.lang.Thread.State: RUNNABLE
at java.net.PlainSocketImpl.socketAccept(Native Method)
at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:409)
at java.net.ServerSocket.implAccept(ServerSocket.java:545)
at java.net.ServerSocket.accept(ServerSocket.java:513)
at sun.management.jmxremote.LocalRMIServerSocketFactory$1.accept(LocalRMIServerSocketFactory.java:52)
at sun.rmi.transport.tcp.TCPTransport$AcceptLoop.executeAcceptLoop(TCPTransport.java:400)
at sun.rmi.transport.tcp.TCPTransport$AcceptLoop.run(TCPTransport.java:372)
at java.lang.Thread.run(Thread.java:748)
Locked ownable synchronizers:
- None
"DestroyJavaVM" #16 prio=5 os_prio=31 tid=0x00007fe2c90cf800 nid=0x2803 waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
Locked ownable synchronizers:
- None
"t3" #14 prio=5 os_prio=31 tid=0x00007fe2c7865000 nid=0x5503 waiting for monitor entry [0x000070000b56e000]
java.lang.Thread.State: BLOCKED (on object monitor)
at com.lkf.mulithread.SyncThread.run(ThreadDeadlock.java:40)
- waiting to lock <0x0000000797618188> (a java.lang.Object)
- locked <0x0000000797618198> (a java.lang.Object)
at java.lang.Thread.run(Thread.java:748)
Locked ownable synchronizers:
- None
"Attach Listener" #15 daemon prio=9 os_prio=31 tid=0x00007fe2c884d800 nid=0xb07 waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
Locked ownable synchronizers:
- None
"t2" #13 prio=5 os_prio=31 tid=0x00007fe2c884b800 nid=0x3e03 waiting for monitor entry [0x000070000b368000]
java.lang.Thread.State: BLOCKED (on object monitor)
at com.lkf.mulithread.SyncThread.run(ThreadDeadlock.java:40)
- waiting to lock <0x0000000797618198> (a java.lang.Object)
- locked <0x00000007976181e8> (a java.lang.Object)
at java.lang.Thread.run(Thread.java:748)
Locked ownable synchronizers:
- None
"t1" #12 prio=5 os_prio=31 tid=0x00007fe2c7885000 nid=0x4103 waiting for monitor entry [0x000070000b265000]
java.lang.Thread.State: BLOCKED (on object monitor)
at com.lkf.mulithread.SyncThread.run(ThreadDeadlock.java:40)
- waiting to lock <0x00000007976181e8> (a java.lang.Object)
- locked <0x0000000797618188> (a java.lang.Object)
at java.lang.Thread.run(Thread.java:748)
Locked ownable synchronizers:
- None
"Service Thread" #11 daemon prio=9 os_prio=31 tid=0x00007fe2c884c800 nid=0x4503 runnable [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
Locked ownable synchronizers:
- None
"C1 CompilerThread2" #10 daemon prio=9 os_prio=31 tid=0x00007fe2c906c000 nid=0x4603 waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
Locked ownable synchronizers:
- None
"C2 CompilerThread1" #9 daemon prio=9 os_prio=31 tid=0x00007fe2c884a800 nid=0x3c03 waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
Locked ownable synchronizers:
- None
"C2 CompilerThread0" #8 daemon prio=9 os_prio=31 tid=0x00007fe2c806c800 nid=0x3a03 waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
Locked ownable synchronizers:
- None
"JDWP Command Reader" #7 daemon prio=10 os_prio=31 tid=0x00007fe2c7811000 nid=0x4903 runnable [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
Locked ownable synchronizers:
- None
"JDWP Event Helper Thread" #6 daemon prio=10 os_prio=31 tid=0x00007fe2c7810000 nid=0x3803 runnable [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
Locked ownable synchronizers:
- None
"JDWP Transport Listener: dt_socket" #5 daemon prio=10 os_prio=31 tid=0x00007fe2c780f800 nid=0x4a07 runnable [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
Locked ownable synchronizers:
- None
"Signal Dispatcher" #4 daemon prio=9 os_prio=31 tid=0x00007fe2c801d000 nid=0x3507 runnable [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
Locked ownable synchronizers:
- None
"Finalizer" #3 daemon prio=8 os_prio=31 tid=0x00007fe2c7820800 nid=0x3003 in Object.wait() [0x000070000a847000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:143)
- locked <0x0000000797618850> (a java.lang.ref.ReferenceQueue$Lock)
at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:164)
at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:209)
Locked ownable synchronizers:
- None
"Reference Handler" #2 daemon prio=10 os_prio=31 tid=0x00007fe2c8017000 nid=0x2e03 in Object.wait() [0x000070000a744000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:502)
at java.lang.ref.Reference.tryHandlePending(Reference.java:191)
- locked <0x0000000797618890> (a java.lang.ref.Reference$Lock)
at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:153)
Locked ownable synchronizers:
- None
"VM Thread" os_prio=31 tid=0x00007fe2c8014800 nid=0x5303 runnable
"GC task thread#0 (ParallelGC)" os_prio=31 tid=0x00007fe2c8011800 nid=0x1b07 runnable
"GC task thread#1 (ParallelGC)" os_prio=31 tid=0x00007fe2c8012000 nid=0x1d03 runnable
"GC task thread#2 (ParallelGC)" os_prio=31 tid=0x00007fe2c8012800 nid=0x2a03 runnable
"GC task thread#3 (ParallelGC)" os_prio=31 tid=0x00007fe2c9010000 nid=0x5403 runnable
"VM Periodic Task Thread" os_prio=31 tid=0x00007fe2c781a000 nid=0x4303 waiting on condition
JNI global references: 5038
Found one Java-level deadlock:
=============================
"t3":
waiting to lock monitor 0x00007fe2c91c7198 (object 0x0000000797618188, a java.lang.Object),
which is held by "t1"
"t1":
waiting to lock monitor 0x00007fe2c9046568 (object 0x00000007976181e8, a java.lang.Object),
which is held by "t2"
"t2":
waiting to lock monitor 0x00007fe2c91c5b98 (object 0x0000000797618198, a java.lang.Object),
which is held by "t3"
Java stack information for the threads listed above:
===================================================
"t3":
at com.lkf.mulithread.SyncThread.run(ThreadDeadlock.java:40)
- waiting to lock <0x0000000797618188> (a java.lang.Object)
- locked <0x0000000797618198> (a java.lang.Object)
at java.lang.Thread.run(Thread.java:748)
"t1":
at com.lkf.mulithread.SyncThread.run(ThreadDeadlock.java:40)
- waiting to lock <0x00000007976181e8> (a java.lang.Object)
- locked <0x0000000797618188> (a java.lang.Object)
at java.lang.Thread.run(Thread.java:748)
"t2":
at com.lkf.mulithread.SyncThread.run(ThreadDeadlock.java:40)
- waiting to lock <0x0000000797618198> (a java.lang.Object)
- locked <0x00000007976181e8> (a java.lang.Object)
at java.lang.Thread.run(Thread.java:748)
Found 1 deadlock.
为了分析死锁,我们需要注意那些被阻塞的线程,以及等待锁定的资源,每个资源有一个惟一的ID,我们可以找到哪个线程已经持有对象上的锁,比如:线程t3正在等待获取对象0x00007fe2c91c7198的锁,但是该对象已经被线程t1锁定。
怎么避免死锁
上边,我们分析了死锁的情况,发现了导致死锁的线程,我们需要修改代码以避免死锁的情况,那么怎么避免死锁呢
1、避免嵌套锁
这是死锁最常见的原因,如果您已经持有一个资源,请避免锁定另一个资源。如果只使用一个对象锁,则几乎不可能出现死锁情况,比如以下代码对上边的循环嵌套部分进行修改,则避免了死锁的情况:
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.");
}
2、只锁需要的部分
只获对需要的资源加锁,例如在上面的程序中,我们锁定了完整的对象资源,但是如果我们只需要其中一个字段,那么我们应该只锁定那个特定的字段而不是完整的对象
3、避免无限期等待
如果两个线程使用 thread join 无限期互相等待也会造成死锁,我们可以设定等待的最大时间来避免这种情况。
翻译自:https://www.journaldev.com/1058/deadlock-in-java-example
Java线程之如何分析死锁及避免死锁的更多相关文章
- 【Java线程与内存分析工具】VisualVM与MAT简明教程
目录 前言 VisualVM 安装与配置 本地使用 远程监控 MAT 使用场景 安装与配置 获得堆转储文件 分析堆转储文件 窥探对象内存值 堆转储文件对比分析 总结 前言 本文将简要介绍Java线程与 ...
- Java 线程池原理分析
1.简介 线程池可以简单看做是一组线程的集合,通过使用线程池,我们可以方便的复用线程,避免了频繁创建和销毁线程所带来的开销.在应用上,线程池可应用在后端相关服务中.比如 Web 服务器,数据库服务器等 ...
- 聊聊并发(三)Java线程池的分析和使用
1. 引言 合理利用线程池能够带来三个好处.第一:降低资源消耗.通过重复利用已创建的线程降低线程创建和销毁造成的消耗.第二:提高响应速度.当任务到达时,任务可以不需要的等到线程创建就能立即执行. ...
- JAVA线程dump的分析
Java 的线程 线程是指能独立于程序的其它部分运行的执行单元. JAVA语言能够很好的实现多线程的程序.我们在调试程序,或者在开发后期需要做性能调优的时候,往往也需要了解当前程序正在运行的线程的状态 ...
- 50道Java线程面试题分析及答案
下面是Java线程相关的热门面试题,你可以用它来好好准备面试. 1) 什么是线程?线程是操作系统能够进行运算调度的最小单位,它被包含在进程之中,是进程中的实际运作单位.程序员可以通过它进行多处理器编程 ...
- JAVA线程池的分析和使用
1. 引言 合理利用线程池能够带来三个好处.第一:降低资源消耗.通过重复利用已创建的线程降低线程创建和销毁造成的消耗.第二:提高响应速度.当任务到达时,任务可以不需要等到线程创建就能立即执行.第三:提 ...
- java线程启动原理分析
一.前言不知道哪位古人说:人生三大境界.第一境界是:看山是山看水是水:第二境界是看山不是山看水不是水:第三境界:看山还是山看水还是水.其实我想对于任何一门技术的学习都是这样.形而上下者为之器,形而上者 ...
- Java 线程不安全问题分析
当多个线程并发访问同一个资源对象时,可能会出现线程不安全的问题 public class Method implements Runnable { private static int num=50; ...
- java线程基础巩固---分析Thread的join方法详细介绍,结合一个典型案例
关于Thread中的join方法貌似在实际多线程编程当中没怎么用过,在当初学j2se的时候倒时去学习过它的用法,不过现在早已经忘得差不多啦,所以对它再复习复习下. 首先先观察下JDK对它的介绍: 其实 ...
随机推荐
- Postgresql在Windows下的解压安装
1.将下载的压缩包解压,我是解压在D:\postgreSQL\pgsql中. 2.设置环境变量如下: set PGHOME=D:\postgreSQL\pgsql set PGDATA=%PGH ...
- C# 不用添加WebService引用,调用WebService方法
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行. [System.Web.Script.Services.ScriptService] 使用HttpWeb ...
- url请求
--[[local g = require 'library.global'--__ml_ss = mlc.prefix.ml_psession..tostring(os.time());local ...
- JS基础_条件运算符
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- vue项目性能优化总结
在使用elementUI构建公司管理系统时,发现首屏加载时间长,加载的网络资源比较多,对系统的体验性会差一点,而且用webpack打包的vuejs的vendor包会比较大.所以通过搜集网上所有对于vu ...
- fastadmin中关联表时A为主表,想让B表和C表关联时怎么办?
$sql = Db::connect('数据库')->table('C表')->where('status', 'normal')->field('字段 别称[不可与其他表重复]') ...
- fastadmin 随笔 刷新表格数据 获取当前登录人信息 服务端导出Excel
table.bootstrapTable('refresh',{url:'你的url'}); 获取当前登录人信息 $this->auth就能获取当前用户信息,比如$this->auth-& ...
- /etc/ld.so.conf.d/目录下文件的作用
在了解/etc/ld.so.conf.d/目录下文件的作用之前,先介绍下程序运行是加载动态库的几种方法: 第一种,通过ldconfig命令 ldconfig命令的用途, 主要是在默认搜寻目录( ...
- Manjaro18+kde 更换壁纸重启失效
更换壁纸 在kde的桌面右键->配置桌面 壁纸里更换壁纸,我不能直接添加图像并应用.我的系统在这样操作后重启就会发现一切都被重置了.刚刚添加的图片也不见了. 于是,我就模范原本存在壁纸文 ...
- 构建虚拟工控环境系列 - 西门子虚拟PLC
一. 概述 跟随着工控安全一路走来,工控安全市场今年明显有相当大的改善,无论从政策还是客户需求,都在逐步扩大中.但是,搞工控安全研究的人员却寥寥无几.一方面工控安全是个跨学课的技术,需要了解多方面的知 ...