Java concurrent programming (3) Avoid Risks of activity, java concurrency
Active hazard 1. deadlock
Occurrence: Everyone does not want to give up their locks. They really want others' locks, which will lead to deadlocks.
1.Lock sequence deadlock: If each thread acquires the lock in a fixed order, at least the deadlock caused by the lock sequence will not appear in the program;
Because the order is fixed such as: All threads: A-B-C is no problem, a deadlock occurs if a A-B B-A
Example 1: simple deadlock
Public class LeftRightDeadlock {private final Object left = new Object (); private final Object right = new Object (); public void leftRight () {synchronized (left) {// lock left synchronized (right) {// lock right doSomething () ;}}// if one thread enters the preceding method to lock left, the other thread enters the following method to lock right, mutual wait will occur, and the deadlock public void rightLeft () {synchronized (right) {// lock right synchronized (left) {// lock left doSomethingElse ();}}} void doSomething () {}void doSomethingElse (){}}
Example 2: Transfer deadlock
Public static void transferMoney (Account fromAccount, Account toAccount, DollarAmount amount) throws InsufficientFundsException {// transfers a-B and B-a. If both are involved, deadlocks may occur; this depends on the input of the parameter. It is not completely determined that synchronized (fromAccount) {synchronized (toAccount) {if (fromAccount. getBalance (). compareTo (amount) <0) throw new InsufficientFundsException (); else {fromAccount. debit (amount); toAccount. credit (amount );}}}}
2. Resource deadlock
When resources are obtained at the same time, but resources are locked, a deadlock occurs;
For example, an application has two databases, and two threads enter two connection pools. If both connection pools are full, they need to wait for each other to release the connection.
Thread hunger deadlock: it is manifested that the thread pool is insufficient, and the threads in the thread pool wait for each other (A submits B to the single thread pool, right commits C to the single thread pool, but B needs to wait until C completes)
3. Live lock
Does not block the thread, but cannot continue execution.
It is similar to a program that keeps failing and never jumps out.