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 解決方案
使用開放呼叫,開放呼叫指呼叫該方法不需要持有鎖,
開放呼叫,是指在呼叫某個方法時不需要持有鎖,開放呼叫可以避免死鎖,這種代碼更容易撰寫,上述調度演算法完全可以修改為開發呼叫,修改同步代碼塊的范圍,使其僅用于保護那些涉及共享狀態的操作,避免在同步代碼塊中執行方法呼叫,修改Dispatcher的reportLocation方法:
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();
}
}
本文由
傳智教育博學谷教研團隊發布,如果本文對您有幫助,歡迎
關注和點贊;如果您有任何建議也可留言評論或私信,您的支持是我堅持創作的動力,轉載請注明出處!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/529829.html
標籤:Java
