I. Description of requirements:
Transferring funds from one account to another.
Second, the implementation of the program:
(1) Account type:
public class Account { private long account; Public account (String user, long account) { this.account = account; } Public account () { super (); } Public long Getaccount () { return account; } public void Setaccount (long account) { this.account = account; } public void Debit (long money) { This.account-=-money; } public void Credits (long money) { This.account + = Money; }}
(2) Asset Transfer category:
public class Transmoney { private static final Object Tielock = new Object (); public static void TransferMoney (account fromaccount,account Toaccount,long amount) { synchronized (fromaccount) { synchronized (toaccount) { fromaccount.debit (amount); Toaccount.credit (amount);}}}
(3) Test class:
public class Demonstratedeadlock { private static final int num_threads =; private static final int num_accounts = 5; private static final int num_iterations = 1000000; public static void Main (string[] args) { final random rdn = new Random (); Final account[] accounts = new account[num_accounts]; for (int. i=0;i<accounts.length;i++) { Accounts[i] = new account (); } Class Transferthread extends thread{public void Run () {for (int i=0;i<num_iterations;i++) { int Fromaccount = Rdn.nextint (num_accounts); int toaccount = Rdn.nextint (num_accounts); Transmoney.transfermoney (Accounts[fromaccount],accounts[toaccount],rdn.nextint ()); }}} for (int i=0;i<num_threads;i++) { new Transferthread (). Start ();}} }
(4) Analysis:
The above procedure is easy to form deadlock, because there is a lock sequence conflict when multiple accounts call Transmoney.transfermoney.
The solution is to use System.identityhashcode to define the order of the locks, eliminating the possibility of deadlocks, and the code is implemented as follows:
public static void TransferMoney (Final account fromaccount,final account toaccount,final long amount) { class helper{ Public void Transfer () { fromaccount.debit (amount); Toaccount.credit (amount); } } int fromhash = System.identityhashcode (fromaccount); int tohash = System.identityhashcode (toaccount); if (Fromhash < Tohash) { synchronized (fromaccount) { synchronized (toaccount) { new Helper (). Transfer (); } } } else if (Fromhash > Tohash) { synchronized (toaccount) { synchronized (fromaccount) { new Helper (). Transfer ();}}} else{ synchronized (tielock) { synchronized (fromaccount) { synchronized (toaccount) { new Helper (). Transfer ();}}}}
Java Concurrent Programming Learning note------Lock sequence deadlock