Active Danger One, deadlock
Occurrence: Everyone is unwilling to give up their locks, do want someone else's lock, which will lead to deadlock
1. Lock sequence Deadlock : If each thread acquires a lock in a fixed order, then at least there will be no deadlock caused by the lock order in the program;
Because the order is fixed such as: All Threads: a-b-c is not a problem, if a A-B b-a will occur deadlock
Example 1: Simple deadlock
Public classLeftrightdeadlock {Private FinalObject left =NewObject (); Private FinalObject right =NewObject (); Public voidleftright () {synchronized(left) {//Lock Left synchronized(right) {//Lock Right.dosomething (); } } } //If a thread enters the method above to lock left and another thread enters the following method to lock right, it will cause a deadlock to wait for each other . Public voidRightleft () {synchronized(right) {//Lock Right. synchronized(left) {//Lock LeftDosomethingelse (); } } } voiddosomething () {}voidDosomethingelse () {}}
Example 2: Transfer a deadlock
Public Static voidTransferMoney (account fromaccount,account toaccount,dollaramount amount)throwsinsufficientfundsexception {//transfer of A-B and b-a, if at the same time, a deadlock may occur, depending on the parameters of the incoming; synchronized(fromaccount) {synchronized(toaccount) {if(Fromaccount.getbalance (). CompareTo (amount) < 0) Throw Newinsufficientfundsexception (); Else{fromaccount.debit (amount); Toaccount.credit (amount); } } } }
2. Resource deadlock
While acquiring resources while resources are locked together, deadlocks can occur;
Such as: An application has two databases, just two threads into two connection pools, two connection pools are full, you need to wait for each other to release the connection
Thread starvation deadlock: Performance as thread pool is not enough, line Cheng threads wait for each other (a commits B to a thread pool, right commits C to the thread pool, but B waits for C to finish before execution)
3. Live Lock
Do not block threads, but cannot continue
Like a program constantly trying to fail, never jump out
Java Concurrency Programming (3) Avoid the danger of being active