Java通過鎖的順序避免死結,java順序
內容:通過擷取鎖的順序來避免死結。例如:銀行賬戶轉賬問題,兩個使用者轉賬的話,如果採用一般的synchronized嵌套的話,容易造成死結,現在我們通過類似哲學家問題的解決方案一樣:先擷取同一個鎖,才有資格擷取下一個。而判斷是通過System.identityHashCode()來產生類的hashcode()的返回值作為唯一標識,相同的話,我們再加一把鎖。
class Account {private int money;public Account(int money) {this.money = money;}public void debit(int amount) {System.out.println("after debit " + amount + " " + this.money + " -> " + (this.money-amount));this.money -= amount;}public void credit(int amount) {System.out.println("after credit " + amount + " " + this.money + " -> " + (this.money+amount));this.money += amount;}public int get() {return this.money;}}public class OrderLock {private static final Object tieLock = new Object();public void transferMoney(final Account fromAcct, final Account toAcct, final int amount) throws InsufficientResourcesException {class Helper {public void transfer() throws InsufficientResourcesException {if (fromAcct.get() < amount) throw new InsufficientResourcesException();else {fromAcct.debit(amount);toAcct.credit(amount);}}}int fromHash = System.identityHashCode(fromAcct);int toHash = System.identityHashCode(toAcct);if (fromHash < toHash) {synchronized (fromAcct) {synchronized (toAcct) {new Helper().transfer();}}} else if (fromHash > toHash) {synchronized (toAcct) {synchronized (fromAcct) {new Helper().transfer();}}} else {synchronized (tieLock) {synchronized (fromAcct) {synchronized (toAcct) {new Helper().transfer();}}}}}class MyThread implements Runnable {private Account fromAcct;private Account toAcct;private int amount;public MyThread(Account fromAcct, Account toAcct, int amount) {this.fromAcct = fromAcct;this.toAcct = toAcct;this.amount = amount;}@Overridepublic void run() {try {transferMoney(this.fromAcct, this.toAcct, this.amount);} catch (InsufficientResourcesException e) {System.out.println("操作失敗");}}}public static void main(String[] args) {Account fromAcct = new Account(100);Account toAcct = new Account(230);OrderLock orderLock = new OrderLock();ExecutorService threadPool = Executors.newCachedThreadPool();for (int i = 0; i < 5; i++) {if ((i & 1) == 0)threadPool.execute(orderLock.new MyThread(fromAcct, toAcct, 10));else threadPool.execute(orderLock.new MyThread(toAcct, fromAcct, 10));}}}