併發編程之死鎖解析

在 Java 的併發編程中,有一個問題須要特別注意,那就是死鎖,若是發生了死鎖,基本就是重啓,而重啓將會丟失運行中的數據。因此,瞭解死鎖的造成並排查死鎖到預防死鎖成了一個重要的問題。
1.什麼是死鎖
[Java] 純文本查看 複製代碼
?java

public class DeadLock {編程

public static void main(String[] args) {併發

new Thread(() -> {
  try {
     new DeadLock().resource1();
  } catch (InterruptedException e) {
  }
}
).start();

new Thread(() -> {
  try {
     new DeadLock().resource2();
  } catch (InterruptedException e) {
  }
}
).start();

}app

void resource1() throws InterruptedException {socket

synchronized ("resource1") {
  System.out.println("獲取資源1");
   // 等待 1 秒讓另外一個線程拿到鎖
  Thread.sleep(1000);
  resource2();
}

}spa

void resource2() throws InterruptedException {.net

synchronized ("resource2") {
  System.out.println("獲取資源2");
  // 等待 1 秒讓另外一個線程拿到鎖
  Thread.sleep(1000);
  resource1();
}

}
}線程

上面的代碼中,咱們啓用了兩個線程,分別搶佔2個資源,但這兩個資源又分別被不一樣的對象(字符串)鎖住了。當第一個線程調用 resource1 方法,進入同步塊,拿到鎖,並等待 1 秒鐘讓另外一個線程進入 resource2 同步塊,當第二個線程進入同步塊後,注意:此時, 拿着 resourec1 鎖的線程企圖拿到 resource2 的鎖,但這個時候,拿着 resource2 的線程也想去拿 resource1 的鎖。因而就出現了互相僵持的狀況,誰也沒法拿到對方的鎖,整個系統就卡死了。
2.如何檢測死鎖
[Java] 純文本查看 複製代碼
?code

Full thread dump Java HotSpot(TM) Client VM (25.131-b11 mixed mode):orm

"DestroyJavaVM" #11 prio=5 os_prio=0 tid=0x051fe800 nid=0x1e0c waiting on condition [0x00000000]
java.lang.Thread.State: RUNNABLE

"Thread-1" #10 prio=5 os_prio=0 tid=0x18777800 nid=0x5664 waiting for monitor entry [0x18e0f000]
java.lang.Thread.State: BLOCKED (on object monitor)

at hello.DeadLock.resource1(DeadLock.java:31)
    - waiting to lock <0x07415a50> (a java.lang.String)
    at hello.DeadLock.resource2(DeadLock.java:43)
    - locked <0x0742bd18> (a java.lang.String)
    at hello.DeadLock.lambda$main$1(DeadLock.java:20)
    at hello.DeadLock$$Lambda$2/4983748.run(Unknown Source)
    at java.lang.Thread.run(Thread.java:748)

"Thread-0" #9 prio=5 os_prio=0 tid=0x18776c00 nid=0x4dc4 waiting for monitor entry [0x18d7f000]
java.lang.Thread.State: BLOCKED (on object monitor)

at hello.DeadLock.resource2(DeadLock.java:41)
    - waiting to lock <0x0742bd18> (a java.lang.String)
    at hello.DeadLock.resource1(DeadLock.java:33)
    - locked <0x07415a50> (a java.lang.String)
    at hello.DeadLock.lambda$main$0(DeadLock.java:11)
    at hello.DeadLock$$Lambda$1/5592464.run(Unknown Source)
    at java.lang.Thread.run(Thread.java:748)

"Service Thread" #8 daemon prio=9 os_prio=0 tid=0x186e4c00 nid=0x172c runnable [0x00000000]
java.lang.Thread.State: RUNNABLE

"C1 CompilerThread0" #7 daemon prio=9 os_prio=2 tid=0x186af000 nid=0x53f8 waiting on condition [0x00000000]
java.lang.Thread.State: RUNNABLE

"Monitor Ctrl-Break" #6 daemon prio=5 os_prio=0 tid=0x1861e800 nid=0x3928 runnable [0x18b3f000]
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 sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
    at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
    at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
    - locked <0x07861da0> (a java.io.InputStreamReader)
    at java.io.InputStreamReader.read(InputStreamReader.java:184)
    at java.io.BufferedReader.fill(BufferedReader.java:161)
    at java.io.BufferedReader.readLine(BufferedReader.java:324)
    - locked <0x07861da0> (a java.io.InputStreamReader)
    at java.io.BufferedReader.readLine(BufferedReader.java:389)
    at com.intellij.rt.execution.application.AppMainV2$1.run(AppMainV2.java:64)

"Attach Listener" #5 daemon prio=5 os_prio=2 tid=0x179c0800 nid=0x40a0 waiting on condition [0x00000000]
java.lang.Thread.State: RUNNABLE

"Signal Dispatcher" #4 daemon prio=9 os_prio=2 tid=0x17985c00 nid=0x5004 runnable [0x00000000]
java.lang.Thread.State: RUNNABLE

"Finalizer" #3 daemon prio=8 os_prio=1 tid=0x17972400 nid=0x41a8 in Object.wait() [0x17cff000]
java.lang.Thread.State: WAITING (on object monitor)

at java.lang.Object.wait(Native Method)
    - waiting on <0x0ca1b830> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:143)
    - locked <0x0ca1b830> (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)

"Reference Handler" #2 daemon prio=10 os_prio=2 tid=0x17960000 nid=0x4ef0 in Object.wait() [0x17c6f000]
java.lang.Thread.State: WAITING (on object monitor)

at java.lang.Object.wait(Native Method)
    - waiting on <0x0ca1b9d0> (a java.lang.ref.Reference$Lock)
    at java.lang.Object.wait(Object.java:502)
    at java.lang.ref.Reference.tryHandlePending(Reference.java:191)
    - locked <0x0ca1b9d0> (a java.lang.ref.Reference$Lock)
    at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:153)

"VM Thread" os_prio=2 tid=0x1795a800 nid=0x3f54 runnable

"VM Periodic Task Thread" os_prio=2 tid=0x18739400 nid=0x4a14 waiting on condition

JNI global references: 229

// 找到一個死鎖

Found one Java-level deadlock:

"Thread-1":
waiting to lock monitor 0x17978de4 (object 0x07415a50, a java.lang.String),
which is held by "Thread-0"
"Thread-0":
waiting to lock monitor 0x1797a974 (object 0x0742bd18, a java.lang.String),
which is held by "Thread-1"

Java stack information for the threads listed above:

"Thread-1":

at hello.DeadLock.resource1(DeadLock.java:31)
     // 等待 0x07415a50 鎖
    - waiting to lock <0x07415a50> (a java.lang.String)
    at hello.DeadLock.resource2(DeadLock.java:43)
    // 持有 0x0742bd18
    - locked <0x0742bd18> (a java.lang.String)
    at hello.DeadLock.lambda$main$1(DeadLock.java:20)
    at hello.DeadLock$$Lambda$2/4983748.run(Unknown Source)
    at java.lang.Thread.run(Thread.java:748)

"Thread-0":

at hello.DeadLock.resource2(DeadLock.java:41)
    // 等待 0x0742bd18 鎖
    - waiting to lock <0x0742bd18> (a java.lang.String)
    at hello.DeadLock.resource1(DeadLock.java:33)
    // 持有 0x07415a50
    - locked <0x07415a50> (a java.lang.String)
    at hello.DeadLock.lambda$main$0(DeadLock.java:11)
    at hello.DeadLock$$Lambda$1/5592464.run(Unknown Source)
    at java.lang.Thread.run(Thread.java:748)

// 發現了一個死鎖
Found 1 deadlock.

3.死鎖造成的緣由
互斥條件:一個資源每次只能被一個線程使用。
請求與保持條件:一個進程因請求資源而阻塞時,對已得到的資源保持不放。
不剝奪條件:進程已得到的資源,在未使用完以前,不能強行剝奪。
循環等待條件:若干進程之間造成一種頭尾相接的循環等待資源關係。

死鎖是由四個必要條件致使的,因此通常來講,只要破壞這四個必要條件中的一個條件,死鎖狀況就應該不會發生。若是想要打破互斥條件,咱們須要容許進程同時訪問某些資源,這種方法受制於實際場景,不太容易實現條件;打破不可搶佔條件,這樣須要容許進程強行從佔有者那裏奪取某些資源,或者簡單一點理解,佔有資源的進程不能再申請佔有其餘資源,必須釋放手上的資源以後才能發起申請,這個其實也很難找到適用場景;進程在運行前申請獲得全部的資源,不然該進程不能進入準備執行狀態。這個方法看似有點用處,可是它的缺點是可能致使資源利用率和進程併發性下降;避免出現資源申請環路,即對資源事先分類編號,按號分配。這種方式能夠有效提升資源的利用率和系統吞吐量,可是增長了系統開銷,增大了進程對資源的佔用時間。

相關文章
相關標籤/搜索