Java synchronization mechanism of deadlock

Java Concurrency side story series - synchronization mechanisms (c)

Companion " the synchronized synchronization mechanisms of the Java " companion " volatile synchronization mechanisms of the Java "

Refers to two or more processes in the implementation process, a result of competition for resources caused by the phenomenon of waiting for each other, the absence of external forces, they will not be able to promote it.

First look at a news:

"ATT" is the common international standards for the supervision of the United Nations eight categories of conventional weapons in international trade established by the treaty by the UN General Assembly on April 2, 2013. June 3, 2013 at United Nations Headquarters in New York is open for signature by all States, the national day of the signing of more than 60. However, the United States, China and Russia, the three permanent members of the Security Council did not sign the same day. Later, the largest arms-producing and exporting countries the United States signed the treaty, but did not formally approved. China and Russia have not yet signed the treaty. April 26, 2019, the American Rifle Association annual meeting US President Trump held in Indiana announced, "ATT" is a "serious misleading of the treaty," the United States will withdraw the signature on the treaty. Trump will ask the Senate to stop the ratification process of the treaty, the US withdrawal from the United Nations' Arms Trade Treaty. "

In fact is this: the United States: Russia, etc. I first signed I signed it; Russia: I'll wait for China to sign me to sign; China: I'll wait for the United States first signed I signed it;

Well, ranging up. Because of the deadlock.

The sample code

When a thread forever hold a lock, thread and other threads trying to acquire the lock, then they will never be blocked. In A thread that holds the lock and want to get a lock b, b thread B holds the lock and try to get a, then the two threads will always wait. This case is the most simple form of deadlock:

public class TestDead {
    private Object a;
    private Object b;

    public TestDead(Object a, Object b) {

        this.a = a;
        this.b = b;
    }

    public void funOne(){
        synchronized (a){
            System.out.println("finOne");
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            funTwo();
        }
    }
    public void funTwo(){
        synchronized (b){
            System.out.println("finTwo");
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            funOne();
        }
    }

}

TestDead testDead = new TestDead(new Object(), new Object());
new Thread(new Runnable() {
            @Override
            public void run() {
                testDead.funOne();
            }
        }).start();
new Thread(new Runnable() {
            @Override
            public void run() {
                testDead.funTwo();
            }
        }).start();
复制代码

Operating results of the program are as follows:

The above code will result in suspended animation thread, in the absence of external forces. Two threads will always be in blocking state, waiting for a lock never be released.

Generate the necessary conditions for deadlock

  • Mutually exclusive conditions: refers to the process of resource allocation to be exclusive use of a resource that is occupied by only one process at a time. If at this time there are other resources to process the request, the requestor can only wait until the share of resources used up in the process of release.
  • Possession and wait: that the process has been maintained for at least one resource, but proposed a new resource request, the resource has been occupied by other processes, this time requesting process blocked, but for other resources that they have available to keep hold.
  • Do not force plays: Resource refers to the process have been obtained before is not used, can not be denied, can only be released by themselves when you are finished.
  • Loop wait condition: refers to a deadlock occurs, there is a necessary process - endless chain of resources, i.e., the process set {P0, P1, P2, ···, Pn} of P0 is waiting for a resource occupied P1; P1 P2 is waiting for resources occupied, ......, Pn is waiting for a resource that has been occupied by P0.

These four conditions are necessary conditions for deadlock, as long as the system deadlock, the establishment of these conditions are inevitable, but as long as one of the above conditions are not met, it will not happen deadlock.

Avoid deadlock and diagnosis

Like many other concurrent dangerous effects caused by the deadlock rarely presented immediately. If a class is possible deadlock, it does not mean that every time a deadlock occurs, but only that it is possible. When the deadlock occurs, often at the worst possible moment - under high load conditions. Deadlock above may be produced by the code lock 查看是否存在嵌套的锁获取操作check whether a deadlock may exist. But sometimes acquire multiple locks operation and not be so obvious.

To avoid problems of deadlock, only requires the destruction of any of the four conditions can be:

  • Breaking mutually exclusive conditions. That process allows for simultaneous access to certain resources. Of course, this approach is not a wide range of trial, because some resources do not allow concurrent access, or there is thread-safety issues.
  • Possession of break and wait condition. Then by the provisions in any case, after a thread obtains a lock, the lock must be returned to request another lock
  • Break can not be preempted conditions. Unless the thread has its own key, otherwise the thread will always occupy the key is not to seize the causes of the condition. It allows a process to forcibly taken possession of some resource persons from there. That is, when a process has accounted for some resources, it apply for new resources, but can not immediately be satisfied, it must release all the resources occupied, later re-apply.
  • Wait for conditions to break the cycle. With this strategy, namely the resource prior classification number assigned by number, you can order any thread take mandatory locks.

Other dangerous activity

Despite the deadlock is the most common activity dangerous, but there are still some concurrent other dangerous activity, including: hunger, live locks, etc.

Hunger: When a thread Unable to access the resources it needs and can not continue, occurs hunger. The most common resources caused by hunger is the CPU clock cycles. If the priority is used improperly, or that can not be the end of the operation (infinite loop) while holding the lock, it is possible to produce thread starvation, because other threads need this lock will never be able to get it.

Livelock: I gave it a mythical name 西西弗斯锁, The Myth of Sisyphus This is another form of active issues, although it does not block the thread, but they can not continue down, because the thread will repeat perform the same operation, and will always fail. When multiple threads are cooperating with each other to respond to modify their status, and any one thread can not be executed, it will livelock. Livelock usually occurs in the code that handles affairs: If you can not successfully process a message, then the message handling mechanism will roll back the entire transaction, and reposition it at the beginning of the queue. Therefore, the code that handles the transaction will be called repeatedly, and returns the same erroneous results, although the message processing thread is not blocked, but can not be implemented.

summary

Deadlock (as well as other active issues) is a very serious problem, because when it appears, in addition to suspend the application outside of no other way to fix this fault. The design should 确保线程在获取多个锁时采用一致性的顺序.

Guess you like

Origin juejin.im/post/5d655cc26fb9a06ace525f8b