Java avoids deadlocks by locking the order, java order
Content: avoid deadlocks by obtaining the lock sequence. For example, if two users transfer funds in a bank account and synchronized Nesting is used, the deadlock may easily occur. Now we use the solution similar to the philosopher's problem: only when the same lock is obtained can the next lock be obtained. The System. identityHashCode () is used to generate the return value of the hashcode () class as the unique identifier. If the same, we will add a lock.
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 ("operation failed") ;}} 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.exe cute (orderLock. new MyThread (fromAcct, toAcct, 10); else threadPool.exe cute (orderLock. new MyThread (toAcct, fromAcct, 10 ));}}}