Chapter 10 of Java concurrent programming practices to avoid activity risks

Source: Internet
Author: User


1. deadlock: a deadlock occurs when two or more processes compete for resources during execution. If there is no external force, they will not be able to proceed. Encyclopedia

When two or more computing units are waiting for the other party to stop running to obtain system resources, but no one exits early, this situation is called a deadlock. Wikipedia


1. A sequential deadlock has at least two locks. One thread needs to obtain the lock before it can operate. The other thread needs to obtain the lock before it can perform the operation, in this case, sequential deadlocks may easily occur.
public class LeftRightDeadlock {private final Object left = new Object();private final Object right = new Object();public void leftRight() {synchronized (left) {synchronized (right) {// doSomething();}}}public void rightLeft() {synchronized (right) {synchronized (left) {// doSomething();}}}}



2. Dynamic lock sequence deadlock
public void transferMoney(Account fromAccount, Account toAccount, DollarAmount anount)throws InsufficientResourcesException {synchronized (fromAccount) {synchronized (toAccount) {if (fromAccount.getBalance().compareTo(amount) < 0) {throw new InsufficientResourcesException();} else {fromAccount.debit(anount);toAccount.credit(anount);}}}}

A: transferMoney (myAccount, yourAccount, 10 );
B: transferMoney (yourAccount, myAccount, 20 );

All the lock conditions of variables passed in from the outside, but the variables passed in above can be seen. In this case, a thread first obtains the myAccount lock and applies for the yourAccount lock, on the contrary, the other thread first acquires the yourAccount lock before applying for the myAccount lock.
private static final Object tieLock = new Object();public void transferMoney(final Account fromAccount, final Account toAccount, final DollarAmount anount)throws InsufficientResourcesException {class Helper{    public void transfer() throws InsufficientResourcesException {        if (fromAccount.getBalance().compareTo(amount) < 0){        throw new InsufficientResourcesException();        } else{fromAccount.debit(anount);toAccount.credit(anount);        }    }}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();            }        }    }}}

3. deadlock between collaboration objects
class Taxi {private Point location, destination;private final Dispatcher dispatcher;public Taxi(Dispatcher dispatcher) {    this.dispatcher = dispatcher;}public synchronized Point getLocation(){    return location;}public synchronized void setLocation(Point location){    this.location = location;    if (location.equals(destination)){        dispatcher.notifyAvaliable(this);    }}} class Dispatcher {private final Set
 
   taxis;private final Set
  
    avaliableTaxis;public Dispatcher(){    taxis = new HashSet
   
    ();    avaliableTaxis = new HashSet
    
     ();}public synchronized void notifyAvaliable(Taxi taxi) {    avaliableTaxis.add(taxi);}public synchronized Image getImage(){    Image image = new Image();    for (Taxi t :taxis){        image.drawMarker(t.getLocation());    }    return image;}}
    
   
  
 

4. Open call-waiting for filling
5. Resource deadlocks external locks are often ignored and lead to deadlocks, such as database locks.
Ii. deadlock prevention and diagnosis 1. Support for timed deadlocks, such as Lock tryLock and Phaser introduced in JDK 7.

2. Analyze the StackTrace of the Dump thread through the thread Dump information. For example, run the command kill-3 in linux. , Or jstack-l Or use the Jconsole to connect to view the StackTrace of the thread to diagnose the deadlock.

3. Other active risks 1. Hunger 2. Poor responsiveness 3. Live locks


4. The use of locks uses data structures that support CAS to avoid locks, such as AtomicXXX, ConcurrentMap, CopyOnWriteList, and concurrent1_queue deadlocks, the ostrich strategy is adopted by many basic frameworks. Methods for Detecting deadlocks

V. References: "Wen shaojin-Java concurrent Programming Tutorial"


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.