Java Concurrency Programming Series 12: Deadlock, starvation and live lock __ concurrent programming

Source: Internet
Author: User
Tags dateformat

Deadlocks occur when a thread needs to acquire multiple resources, and deadlock is the most common active problem because two of threads are blocked from each other for each other's resources. Here we first analyze the deadlock situation:

Assuming that the current situation is that thread A has acquired the resource R1, thread B has acquired the resource R2, and then thread a attempts to acquire the resource R2, and since the resource R2 has been obtained by thread B, thread A can only block until thread B frees the resource R2. Thread B, on the other hand, tries to acquire the resource R1 held by thread A while it has obtained resource R2, so thread B can only be blocked until thread a frees up the resource R1 because the resource R1 has been held by thread A. This causes both thread A and thread B to wait for resources held by the other side, causing a deadlock. This situation is governed by a technical term: sequential deadlock. There are also dynamic deadlocks, collaborative deadlocks, and resource deadlocks, which are essentially the same: the entire program cannot continue down because it waits for resources that are occupied by other threads.

The following program demonstrates the case of sequential deadlocks:

Package com.rhwayfun.concurrency;
Import Java.text.DateFormat;
Import Java.text.SimpleDateFormat;
Import Java.util.Date;

Import Java.util.concurrent.TimeUnit;
 /** * Created by Rhwayfun on 16-4-3.

    * * Public class Deadlock {private static DateFormat format = new SimpleDateFormat ("HH:mm:ss"); Public synchronized void Tryother (deadlock other) throws Interruptedexception {System.out.println (Thread.currentt
        Hread (). GetName () + "Enter Tryother method at" + Format.format (new Date ());
        TimeUnit.SECONDS.sleep (3); System.out.println (Thread.CurrentThread (). GetName () + Tryother method Yes about to invoke the other method at "+ Format.form
        At (new Date ());
    Other.other (); Public synchronized void Other () throws Interruptedexception {System.out.println (Thread.CurrentThread (). GE
        Tname () + "enter" at "+ Format.format (new Date ());
    TimeUnit.SECONDS.sleep (3); public static void Main (string[] args) throws interruptedexception {Final deadlock D1 = new deadlock ();

        Final deadlock D2 = new Deadlock (); thread T1 = new Thread (new Runnable () {public void run () {try {D1.tryot
                Her (D2);
                catch (Interruptedexception e) {e.printstacktrace ();

        }}, "Threada"); Thread t2 = new Thread (new Runnable () {public void run () {try {D2.tryot
                Her (D1);
                catch (Interruptedexception e) {e.printstacktrace ();

        }}, "threadb");
        T1.start ();
        Let Threada first run a second TimeUnit.SECONDS.sleep (1);

        T2.start ();
        After running for 10 seconds, the thread TimeUnit.SECONDS.sleep (10) is tried;
        T1.interrupt ();

        T2.interrupt ();
        System.out.println ("Is Threada is interrupted?" + t1.isinterrupted ()); System.out.println ("is Threadb is interrupted?
    "+ t2.isinterrupted ());
 }
}

The results of the operation are as follows:

You can see that Threada and threadb did not enter into the other method, stating that the program had a deadlock, Threada waiting for threadb resources, threadb waiting for Threada resources (here because of the synchronization method used, So the resource exactly refers to the object-level lock of the D1 and D2, which causes the deadlock. While there is no good way to avoid deadlocks in Java, it is useful to follow some rules in programming to minimize the occurrence of deadlocks: minimizing the scope of the lock, such as using a synchronized code block without using a synchronous method to try to write code that acquires multiple locks at pass time. Because when a thread holds multiple resources it is very easy to deadlock according to the situation will be a large range of locks, so that the scope of each lock is reduced, thus reducing the probability of deadlock occurrence. This is a typical application of the principle of concurrenthashmap locking technology, you can refer to this article.

Hunger refers to a thread that does not have access to the resources it needs to continue execution, the most common source of hunger is the CPU clock cycle. Although a mechanism that specifies thread precedence in the thread API, but only as a reference to the operating system for thread scheduling, in other words, the operating system is platform-independent and provides as fair and active a schedule as possible, even if a thread's priority is specified in the program, It is also possible to map to the same priority when the operating system is scheduled. In general, do not modify the priority of the thread, once the modification of the program will be related to the platform, and will lead to the emergence of hunger problems. The Thread.yield or thread.sleep used in the program indicates that the program attempts to service priority adjustment issues, so that the lower priority thread has the opportunity to be CPU-scheduled.

A Live lock is a thread that repeatedly performs the same operation, but the results of each operation are unsuccessful. Although this problem does not block threads, the program cannot continue to execute. A live lock usually occurs in an application that processes transactional messages, and the transaction rolls back the entire operation if the transaction cannot be successfully processed. The solution to a live lock is to introduce a random mechanism each time the execution is repeated, so that the program can continue to perform other tasks because of the possibility of a different occurrence.

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.