[JAVA concurrent programming practice] 8. Lock sequence deadlock and java practice

Source: Internet
Author: User

[JAVA concurrent programming practice] 8. Lock sequence deadlock and java practice

Package cn. study. concurrency. ch10; public class Account {private String staffAccount; // Account private String passWord; // passWord private int balance; // Account balance public Account (int money) {this. balance = money;} public String getStaffAccount () {return staffAccount;} public void setStaffAccount (String staffAccount) {this. staffAccount = staffAccount;} public String getPassWord () {return passWord;} public void setPassWord (String passWord) {this. passWord = passWord;} public void debit (int amount) {System. out. println ("outgoing account:" + amount);} public void credit (int amount) {System. out. println ("Transfer Account:" + amount);} public int getBalance () {return balance;} public void setBalance (int balance) {this. balance = balance ;}}

 

Package cn. study. concurrency. ch10; import java. util. concurrent. executorService; import java. util. concurrent. executors; import javax. naming. insufficientResourcesException;/*** the lock sequence is determined to avoid deadlocks * @ author xiaof **/public class DeathLock {public void transferMoney (Account fromAccount, Account toAccount, int amount) throws InsufficientResourcesException {synchronized (fromAccount) {synchronized (toAccount) {// locks in the order of parameters. This is based on the order of parameter call methods if (fromAccount. getBalance () <amount) {// the account balance is insufficient and cannot be transferred throw new InsufficientResourcesException ();} else {fromAccount. debit (amount); toAccount. credit (amount) ;}}}/*** this is used to lock the lock in the hour when the order of the shackles cannot be determined */private static final Object tieLock = new Object (); public static void transferMoney2 (final Account fromAccount, final Account toAccount, final int amount) throws InsufficientResourcesException {/*** auxiliary internal class * @ author xiaof **/class Helper {public void transfer () throws InsufficientResourcesException {// internal class can access external class members at Will // lock in the order of parameters. This is based on the order of the parameter call methods if (fromAccount. getBalance () <amount) {// the account balance is insufficient and cannot be transferred throw new InsufficientResourcesException ();} else {fromAccount. debit (amount); toAccount. credit (amount) ;}}// returns the hash code of the given object. This Code is the same as the Code returned by the default hashCode () method, regardless of whether the class of the given object overwrites hashCode () int fromHash = System. identityHashCode (fromAccount); int toHash = System. identityHashCode (toAccount); // determine the lock order based on the hash value, so the lock order of the same object will be the same if (fromHash <toHash) {synchronized (fromAccount) {synchronized (toAccount) {new Helper (). transfer () ;}} else if (toHash <fromHash) {synchronized (toAccount) {synchronized (fromAccount) {new Helper (). transfer () ;}} else {// if it is unfortunate that the hash value is the same, an overtime mechanism is required to obtain the external lock first, then, the two objects are randomly locked to synchronized (tieLock) {synchronized (fromAccount) {synchronized (toAccount) {new Helper (). transfer () ;}}}} static Account account1 = new Account (999); static Account account2 = new Account (999); public static void main (String [] args) throws InsufficientResourcesException {// deadlock is easy for the first method. // For example, when two methods are called simultaneously, DeathLock dl = new DeathLock (); // at this time, the first call locks account1, and the second call locks account2 // At the same time, the first call requires account2, and the second call requires account1, this leads to a competitive deadlock // dl. transferMoney (account1, account2. 998); // dl. transferMoney (account2, account1, 998); // dl. transferMoney2 (account1, account2, 998); ExecutorService pool = Executors. newFixedThreadPool (10); for (int I = 0; I <5; ++ I) {pool.exe cute (new Runnable () {@ Override public void run () {try {DeathLock. transferMoney2 (account1, account2, 998);} catch (InsufficientResourcesException e) {e. printStackTrace () ;}}) ;}for (int I = 0; I <5; ++ I) {pool.exe cute (new Runnable () {@ Override public void run () {try {DeathLock. transferMoney2 (account2, account1, 998);} catch (InsufficientResourcesException e) {e. printStackTrace () ;}});} pool. shutdown ();}}

Test results:

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.