Java线程之如何分析死锁及避免死锁
程序员文章站
2022-05-22 11:20:09
...
什么是死锁
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
下一篇: 死锁