1. 产生条件
一般来说,要出现死锁问题需要满足以下条件:
- 互斥条件:一个资源每次只能被一个线程使用。
- 请求与保持条件:一个线程因请求资源而阻塞时,对已获得的资源保持不放。
- 不剥夺条件:线程已获得的资源,在未使用完之前,不能强行剥夺。
- 循环等待条件:若干线程之间形成一种头尾相接的循环等待资源关系。
在JAVA编程中,有3种典型的死锁类型:
- 静态的锁顺序死锁
- 动态的锁顺序死锁
- 协作对象之间发生的死锁。
下面来一一介绍这三种死锁:
2.例子
2.1 静态的锁顺序死锁
- a和b两个方法都需要获得A锁和B锁。一个线程执行a方法且已经获得了A锁,在等待B锁;
- 另一个线程执行了b方法且已经获得了B锁,在等待A锁。
- 这种状态,就是发生了静态的锁顺序死锁。
举个例子:
//可能发生静态锁顺序死锁的代码
class StaticLockOrderDeadLock {
private final Object lockA = new Object();
private final Object lockB = new Object();
public void a() {
synchronized (lockA) {
synchronized (lockB) {
System.out.println("function a");
}
}
}
public void b() {
synchronized (lockB) {
synchronized (lockA) {
System.out.println("function b");
}
}
}
}
解决办法: 所有需要多个锁的线程,都要以相同的顺序来获得锁。
//正确的代码
class StaticLockOrderDeadLock {
private final Object lockA = new Object();
private final Object lockB = new Object();
public void a() {
synchronized (lockA) {
synchronized (lockB) {
System.out.println("function a");
}
}
}
public void b() {
synchronized (lockA) {
synchronized (lockB) {
System.out.println("function b");
}
}
}
}
2.2 动态的锁顺序死锁
动态的锁顺序死锁是指两个线程调用同一个方法时,传入的参数颠倒造成的死锁。
举个例子:
- 一个线程调用了transferMoney方法并传入参数accountA,accountB;
- 另一个线程调用了transferMoney方法并传入参数accountB,accountA。
- 此时就可能发生在静态的锁顺序死锁中存在的问题,即:第一个线程获得了accountA锁并等待accountB锁,第二个线程获得了accountB锁并等待accountA锁。
//可能发生动态锁顺序死锁的代码
class DynamicLockOrderDeadLock {
public void transefMoney(Account fromAccount, Account toAccount, Double amount) {
synchronized (fromAccount) {
synchronized (toAccount) {
//...
fromAccount.minus(amount);
toAccount.add(amount);
//...
}
}
}
}
解决方案:使用System.identifyHashCode来定义锁的顺序。确保所有的线程都以相同的顺序获得锁。
class DynamicLockOrderDeadLock {
private final Object myLock = new Object();
public void transefMoney(final Account fromAccount, final Account toAccount, final Double amount) {
class Helper {
public void transfer() {
//...
fromAccount.minus(amount);
toAccount.add(amount);
//...
}
}
int fromHash = System.identityHashCode(fromAccount);
int toHash = System.identityHashCode(toAccount);
if (fromHash < toHash) {
synchronized (fromAccount) {
synchronized (toAccount) {
new Helper().transfer();
}
}
} else if (fromHash > toHash) {
synchronized (toAccount) {
synchronized (fromAccount) {
new Helper().transfer();
}
}
} else {
synchronized (myLock) {
synchronized (fromAccount) {
synchronized (toAccount) {
new Helper().transfer();
}
}
}
}
}
}
2.3 协作对象之间发生的死锁
有时,死锁并不会那么明显,比如两个相互协作的类之间的死锁
举个例子:
- 一个线程调用了Taxi对象的setLocation方法,另一个线程调用了Dispatcher对象的getImage方法。
- 此时可能会发生,第一个线程持有Taxi对象锁并等待Dispatcher对象锁,另一个线程持有Dispatcher对象锁并等待Taxi对象锁
//可能发生死锁
class Taxi {
private Point location, destination;
private final Dispatcher dispatcher;
public Taxi(Dispatcher dispatcher) {
this.dispatcher = dispatcher;
}
public synchronized Point getLocation() {
return location;
}
public synchronized void setLocation(Point location) {
this.location = location;
if (location.equals(destination))
dispatcher.notifyAvailable(this);//外部调用方法,可能等待Dispatcher对象锁
}
}
class Dispatcher {
private final Set<Taxi> taxis;
private final Set<Taxi> availableTaxis;
public Dispatcher() {
taxis = new HashSet<Taxi>();
availableTaxis = new HashSet<Taxi>();
}
public synchronized void notifyAvailable(Taxi taxi) {
availableTaxis.add(taxi);
}
public synchronized Image getImage() {
Image image = new Image();
for (Taxi t : taxis)
image.drawMarker(t.getLocation());//外部调用方法,可能等待Taxi对象锁
return image;
}
}
我们在持有锁的情况下调用了外部的方法,这是非常危险的(可能发生死锁)。为了避免这种危险的情况发生, 我们使用开放调用。如果调用某个外部方法时不需要持有锁,我们称之为开放调用。
解决方案:需要使用开放调用,即避免在持有锁的情况下调用外部的方法。
//正确的代码
class Taxi {
private Point location, destination;
private final Dispatcher dispatcher;
public Taxi(Dispatcher dispatcher) {
this.dispatcher = dispatcher;
}
public synchronized Point getLocation() {
return location;
}
public void setLocation(Point location) {
boolean flag = false;
synchronized (this) {
this.location = location;
flag = location.equals(destination);
}
if (flag)
dispatcher.notifyAvailable(this);//使用开放调用
}
}
class Dispatcher {
private final Set<Taxi> taxis;
private final Set<Taxi> availableTaxis;
public Dispatcher() {
taxis = new HashSet<Taxi>();
availableTaxis = new HashSet<Taxi>();
}
public synchronized void notifyAvailable(Taxi taxi) {
availableTaxis.add(taxi);
}
public Image getImage() {
Set<Taxi> copy;
synchronized (this) {
copy = new HashSet<Taxi>(taxis);
}
Image image = new Image();
for (Taxi t : copy)
image.drawMarker(t.getLocation());//使用开放调用
return image;
}
}
3. 如何排查死锁
1.我们通过jstack拿到该应用程序死锁的线程转储文件.
2.如何获取线程转储文件方法
线程dump: Java Thread dump记录了线程在jvm中的执行信息,可以看成是线程活动的日志。Java线程转储文件有助于分析应用程序和死锁情况中的瓶颈。
- 使用VisualVM Profiler:右键选择线程Dump便会自动生成线程转储文件,当然你也可以连接远程机器对其进行监控和分析
- jstack:jdk自带的工具jstack通过它我们也可以生成应用程序的线程转储文件,只需要两步即可完成:
1>找到应用程序的进程ID
ps -eaf | grep java
2> 输出线程转储信息到文件或控制台
jstack PID >> mydumps.tdump
jstack PID
- jcmd: jdk8中介绍了jcmd工具,在jdk8及以上环境下,可以使用此命令生成线程转储文件
jcmd PID Thread.print
实现一个死锁:
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锁定。
4. 如何避免死锁
(1)持有多个锁的话,锁的顺序要一致
(2)尽量避免锁的嵌套
(3)持有锁的方法尽量不要引用外部对象,可能外部对象也持有你的锁,会造成死锁