1. 什麼是死鎖
在多線程環境中,多個程序可以競争有限數量的資源。當一個程序申請資源時,如果這時沒有可用資源,那麼這個程序進入等待狀态。有時,如果所申請的資源被其他等待程序占有,那麼該等待程序有可能再也無法改變狀态。這種情況稱為死鎖
在Java中使用多線程,就會有可能導緻死鎖問題。死鎖會讓程式一直卡住,不再往下執行。我們隻能通過中止并重新開機的方式來讓程式重新執行。
2. 造成死鎖的原因
- 目前線程擁有其他線程需要的資源
- 目前線程等待其他線程已擁有的資源
- 都不放棄自己擁有的資源
3. 死鎖的必要條件
3.1 互斥
程序要求對所配置設定的資源(如列印機)進行排他性控制,即在一段時間内某資源僅為一個程序所占有。此時若有其他程序請求該資源,則請求程序隻能等待。
3.2 不可剝奪
程序所獲得的資源在未使用完畢之前,不能被其他程序強行奪走,即隻能由獲得該資源的程序自己來釋放(隻能是主動釋放)。
3.3 請求與保持
程序已經保持了至少一個資源,但又提出了新的資源請求,而該資源已被其他程序占有,此時請求程序被阻塞,但對自己已獲得的資源保持不放。
3.4 循環等待
是指程序發生死鎖後,必然存在一個程序–資源之間的環形鍊,通俗講就是你等我的資源,我等你的資源,大家一直等。
4. 死鎖的分類
4.1 靜态順序型死鎖
線程之間形成互相等待資源的環時,就會形成順序死鎖lock-ordering deadlock,多個線程試圖以不同的順序來擷取相同的鎖時,容易形成順序死鎖,如果所有線程以固定的順序來擷取鎖,就不會出現順序死鎖問題
經典案例是LeftRightDeadlock,兩個方法,分别是leftRigth、rightLeft。如果一個線程調用leftRight,另一個線程調用rightLeft,且兩個線程是交替執行的,就會發生死鎖。
public class LeftRightDeadLock {
//左邊鎖
private static Object left = new Object();
//右邊鎖
private static Object right = new Object();
/**
* 現持有左邊的鎖,然後擷取右邊的鎖
*/
public static void leftRigth() {
synchronized (left) {
System.out.println("leftRigth: left lock,threadId:" + Thread.currentThread().getId());
//休眠增加死鎖産生的機率
sleep(100);
synchronized (right) {
System.out.println("leftRigth: right lock,threadId:" + Thread.currentThread().getId());
}
}
}
/**
* 現持有右邊的鎖,然後擷取左邊的鎖
*/
public static void rightLeft() {
synchronized (right) {
System.out.println("rightLeft: right lock,threadId:" + Thread.currentThread().getId());
//休眠增加死鎖産生的機率
sleep(100);
synchronized (left) {
System.out.println("rightLeft: left lock,threadId:" + Thread.currentThread().getId());
}
}
}
/**
* 休眠
*
* @param time
*/
private static void sleep(long time) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//建立一個線程池
ExecutorService executorService = Executors.newFixedThreadPool(10);
executorService.execute(() -> leftRigth());
executorService.execute(() -> rightLeft());
executorService.shutdown();
}
}
輸出:
leftRigth: left lock,threadId:12
rightLeft: right lock,threadId:13
我們發現,12号線程鎖住了左邊要向右邊擷取鎖,13号鎖住了右邊,要向左邊擷取鎖,因為兩邊都不釋放自己的鎖,互不相讓,就産生了死鎖。
4.1.1 解決方案
固定加鎖的順序(針對鎖順序死鎖)
隻要交換下鎖的順序,讓線程來了之後先擷取同一把鎖,擷取不到就等待,等待上一個線程釋放鎖再擷取鎖。
public static void leftRigth() {
synchronized (left) {
...
synchronized (right) {
...
}
}
}
public static void rightLeft() {
synchronized (left) {
...
synchronized (right) {
...
}
}
}
4.2 動态鎖順序型死鎖
由于方法入參由外部傳遞而來,方法内部雖然對兩個參數按照固定順序進行加鎖,但是由于外部傳遞時順序的不可控,而産生鎖順序造成的死鎖,即動态鎖順序死鎖。
上例告訴我們,交替的擷取鎖會導緻死鎖,且鎖是固定的。有時候鎖的執行順序并不那麼清晰,參數導緻不同的執行順序。經典案例是銀行賬戶轉賬,from賬戶向to賬戶轉賬,在轉賬之前先擷取兩個賬戶的鎖,然後開始轉賬,如果這是to賬戶向from賬戶轉賬,角色互換,也會導緻鎖順序死鎖。
/**
* 動态順序型死鎖
* 轉賬業務
*/
public class TransferMoneyDeadlock {
public static void transfer(Account from, Account to, int amount) {
//先鎖住轉賬的賬戶
synchronized (from) {
System.out.println("線程【" + Thread.currentThread().getId() + "】擷取【" + from.name + "】賬戶鎖成功");
//休眠增加死鎖産生的機率
sleep(100);
//在鎖住目标賬戶
synchronized (to) {
System.out.println("線程【" + Thread.currentThread().getId() + "】擷取【" + to.name + "】賬戶鎖成功");
if (from.balance < amount) {
System.out.println("餘額不足");
return;
} else {
from.debit(amount);
to.credit(amount);
System.out.println("線程【" + Thread.currentThread().getId() + "】從【" + from.name + "】賬戶轉賬到【" + to.name + "】賬戶【" + amount + "】元錢成功");
}
}
}
}
private static class Account {
String name;
int balance;
public Account(String name, int balance) {
this.name = name;
this.balance = balance;
}
void debit(int amount) {
this.balance = balance - amount;
}
void credit(int amount) {
this.balance = balance + amount;
}
}
/**
* 休眠
*
* @param time
*/
private static void sleep(long time) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//建立線程池
ExecutorService executorService = Executors.newFixedThreadPool(10);
//建立賬戶A
Account A = new Account("A", 100);
//建立賬戶B
Account B = new Account("B", 200);
//A -> B 的轉賬
executorService.execute(() -> transfer(A, B, 5));
//B -> A 的轉賬
executorService.execute(() -> transfer(B, A, 10));
executorService.shutdown();
}
}
輸出:
線程【12】擷取【A】賬戶鎖成功
線程【13】擷取【B】賬戶鎖成功
然後就沒有然後了,産生了死鎖,我們發現 因為對象的調用關系,産生了互相鎖住資源的問題。
4.2.1 解決方案
根據傳入對象的hashCode硬性确定加鎖順序,消除可變性,避免死鎖。
package com.test.thread.deadlock;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 動态順序型死鎖解決方案
*/
public class TransferMoneyDeadlock {
/**
* 螢幕,第三把鎖,為了方式HASH沖突
*/
private static Object lock = new Object();
/**
* 我們經過上一次得失敗,明白了不能依賴參數名稱簡單的确定鎖的順序,因為參數是
* 具有動态性的,是以,我們改變一下思路,直接根據傳入對象的hashCode()大小來
* 對鎖定順序進行排序(這裡要明白的是如何排序不是關鍵,有序才是關鍵)。
*
* @param from
* @param to
* @param amount
*/
public static void transfer(Account from, Account to, int amount) {
/**
* 這裡需要說明一下為什麼不使用HashCode()因為HashCode方法可以被重寫,
* 是以,我們無法簡單的使用父類或者目前類提供的簡單的hashCode()方法,
* 是以,我們就使用系統提供的identityHashCode()方法,該方法保證無論
* 你是否重寫了hashCode方法,都會在虛拟機層面上調用一個名為JVM_IHashCode
* 的方法來根據對象的存儲位址來擷取該對象的hashCode(),HashCode如果不重寫
* 的話,其實也是通過這個虛拟機層面上的方法,JVM_IHashCode()方法實作的
* 這個方法是用C++實作的。
*/
int fromHash = System.identityHashCode(from);
int toHash = System.identityHashCode(to);
if (fromHash > toHash) {
//先鎖住轉賬的賬戶
synchronized (from) {
System.out.println("線程【" + Thread.currentThread().getId() + "】擷取【" + from.name + "】賬戶鎖成功");
//休眠增加死鎖産生的機率
sleep(100);
//在鎖住目标賬戶
synchronized (to) {
System.out.println("線程【" + Thread.currentThread().getId() + "】擷取【" + to.name + "】賬戶鎖成功");
if (from.balance < amount) {
System.out.println("餘額不足");
return;
} else {
from.debit(amount);
to.credit(amount);
System.out.println("線程【" + Thread.currentThread().getId() + "】從【" + from.name + "】賬戶轉賬到【" + to.name + "】賬戶【" + amount + "】元錢成功");
}
}
}
} else if (fromHash < toHash) {
//先鎖住轉賬的賬戶
synchronized (to) {
System.out.println("線程【" + Thread.currentThread().getId() + "】擷取【" + from.name + "】賬戶鎖成功");
//休眠增加死鎖産生的機率
sleep(100);
//在鎖住目标賬戶
synchronized (from) {
System.out.println("線程【" + Thread.currentThread().getId() + "】擷取【" + to.name + "】賬戶鎖成功");
if (from.balance < amount) {
System.out.println("餘額不足");
return;
} else {
from.debit(amount);
to.credit(amount);
System.out.println("線程【" + Thread.currentThread().getId() + "】從【" + from.name + "】賬戶轉賬到【" + to.name + "】賬戶【" + amount + "】元錢成功");
}
}
}
} else {
//如果傳入對象的Hash值相同,那就加讓加第三層鎖
synchronized (lock) {
//先鎖住轉賬的賬戶
synchronized (from) {
System.out.println("線程【" + Thread.currentThread().getId() + "】擷取【" + from.name + "】賬戶鎖成功");
//休眠增加死鎖産生的機率
sleep(100);
//在鎖住目标賬戶
synchronized (to) {
System.out.println("線程【" + Thread.currentThread().getId() + "】擷取【" + to.name + "】賬戶鎖成功");
if (from.balance < amount) {
System.out.println("餘額不足");
return;
} else {
from.debit(amount);
to.credit(amount);
System.out.println("線程【" + Thread.currentThread().getId() + "】從【" + from.name + "】賬戶轉賬到【" + to.name + "】賬戶【" + amount + "】元錢成功");
}
}
}
}
}
}
private static class Account {
String name;
int balance;
public Account(String name, int balance) {
this.name = name;
this.balance = balance;
}
void debit(int amount) {
this.balance = balance - amount;
}
void credit(int amount) {
this.balance = balance + amount;
}
}
/**
* 休眠
*
* @param time
*/
private static void sleep(long time) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//建立線程池
ExecutorService executorService = Executors.newFixedThreadPool(10);
//建立賬戶A
Account A = new Account("A", 100);
//建立賬戶B
Account B = new Account("B", 200);
//A -> B 的轉賬
executorService.execute(() -> transfer(A, B, 5));
//B -> A 的轉賬
executorService.execute(() -> transfer(B, A, 10));
executorService.shutdown();
}
}
輸出
線程【12】擷取【A】賬戶鎖成功
線程【12】擷取【B】賬戶鎖成功
線程【12】從【A】賬戶轉賬到【B】賬戶【5】元錢成功
線程【13】擷取【B】賬戶鎖成功
線程【13】擷取【A】賬戶鎖成功
線程【13】從【B】賬戶轉賬到【A】賬戶【10】元錢成功
4.3 協作對象間的死鎖
在協作對象之間可能存在多個鎖擷取的情況,但是這些擷取多個鎖的操作并不像在LeftRightDeadLock或transferMoney中那麼明顯,這兩個鎖并不一定必須在同一個方法中被擷取。如果在持有鎖時調用某個外部方法,那麼這就需要警惕死鎖問題,因為在這個外部方法中可能會擷取其他鎖,或者阻塞時間過長,導緻其他線程無法及時擷取目前被持有的鎖。
/**
* 協作對象間的死鎖
*/
public class CoordinateDeadlock {
/**
* Taxi 類
*/
static class Taxi {
private String location;
private String destination;
private Dispatcher dispatcher;
public Taxi(Dispatcher dispatcher, String destination) {
this.dispatcher = dispatcher;
this.destination = destination;
}
public synchronized String getLocation() {
return this.location;
}
/**
* 該方法先擷取Taxi的this對象鎖後,然後調用Dispatcher類的方法時,又需要擷取
* Dispatcher類的this方法。
*
* @param location
*/
public synchronized void setLocation(String location) {
this.location = location;
System.out.println(Thread.currentThread().getName() + " taxi set location:" + location);
if (this.location.equals(destination)) {
dispatcher.notifyAvailable(this);
}
}
}
/**
* 排程類
*/
static class Dispatcher {
private Set<Taxi> taxis;
private Set<Taxi> availableTaxis;
public Dispatcher() {
taxis = new HashSet<Taxi>();
availableTaxis = new HashSet<Taxi>();
}
public synchronized void notifyAvailable(Taxi taxi) {
System.out.println(Thread.currentThread().getName() + " notifyAvailable.");
availableTaxis.add(taxi);
}
/**
* 列印目前位置:有死鎖風險
* 持有目前鎖的時候,同時調用Taxi的getLocation這個外部方法;而這個外部方法也是需要加鎖的
* reportLocation的鎖的順序與Taxi的setLocation鎖的順序完全相反
*/
public synchronized void reportLocation() {
System.out.println(Thread.currentThread().getName() + " report location.");
for (Taxi t : taxis) {
t.getLocation();
}
}
public void addTaxi(Taxi taxi) {
taxis.add(taxi);
}
}
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(10);
final Dispatcher dispatcher = new Dispatcher();
final Taxi taxi = new Taxi(dispatcher, "軟體園");
dispatcher.addTaxi(taxi);
//先擷取dispatcher鎖,然後是taxi的鎖
executorService.execute(() -> dispatcher.reportLocation());
//先擷取taxi鎖,然後是dispatcher的鎖
executorService.execute(() -> taxi.setLocation("軟體園"));
executorService.shutdown();
}
}
4.3.1 解決方案
4.3.1.1 setLocation方法
/**
* 開放調用,不持有鎖期間進行外部方法調用
*
* @param location
*/
public void setLocation(String location) {
synchronized (this) {
this.location = location;
}
System.out.println(Thread.currentThread().getName() + " taxi set location:" + location);
if (this.location.equals(destination)) {
dispatcher.notifyAvailable(this);
}
}
4.3.1.2 reportLocation 方法
/**
* 同步塊隻包含對共享狀态的操作代碼
*/
public synchronized void reportLocation() {
System.out.println(Thread.currentThread().getName() + " report location.");
Set<Taxi> taxisCopy;
synchronized (this) {
taxisCopy = new HashSet<Taxi>(taxis);
}
for (Taxi t : taxisCopy) {
t.getLocation();
}
}