If every thread that needs to lock L and lock M gets the L and M in the same order, then there will be no deadlock.
To solve this problem, you must define the order of the locks and follow that order in the entire application to get the locks.
You can use the System.identityhashcode method when setting the order of locks, which returns the value returned by Object.hashcode.
Private Static FinalObject Tielock =NewObject (); Public voidTransferMoney (FinalAccount Fromacct,FinalAccount Toacct,Finaldollaramount amount)throwsinsufficientfundsexception {classHelper { Public voidTransfer ()throwsinsufficientfundsexception {if(Fromacct.getbalance (). CompareTo (amount) < 0) { Throw Newinsufficientfundsexception (); } Else{fromacct.debit (amount); Toacct.credit (amount); } } } intFromhash =System.identityhashcode (FROMACCT); intTohash =System.identityhashcode (TOACCT); if(Fromhash <Tohash) { synchronized(FROMACCT) {synchronized(TOACCT) {NewHelper (). Transfer (); } } } Else if(Fromhash >Tohash) { synchronized(TOACCT) {synchronized(FROMACCT) {NewHelper (). Transfer (); } } } Else { synchronized(tielock) {synchronized(FROMACCT) {synchronized(TOACCT) {NewHelper (). Transfer (); } } } } }
In rare cases, two objects may have the same hash value, and the order of the locks must be determined in some arbitrary way, and this may re-introduce deadlocks. To avoid this situation, you can use the "overtime (tiebreaking)" lock. Before acquiring two account locks, this "overtime" lock is first obtained to ensure that only one thread obtains the two locks in an unknown order at a time, eliminating the possibility of deadlocks (as long as this mechanism is used consistently). This technique can be a bottleneck for concurrency if there is a common case of hash collisions (this is similar to the case where there is only one lock in the entire program), However, due to the very low frequency of hash collisions in System.identityhashcode, this technology has the greatest security at its lowest cost.
If you do not need to hold a lock when calling a method, this call is called an open call.
Use open calls as much as possible in your program. It is easier to deadlock analyze a program that relies on open calls than a program that calls an external method while holding a lock.
Avoid using thread precedence because it increases platform dependencies and can lead to active issues. In most concurrent applications, the default thread priority can be used.
10th chapter to avoid the danger of being active