Java Threading-Deadlock (deadlock)

Source: Internet
Author: User

One, deadlock

Deadlock refers to a situation like this. When multiple threads compete for scarce resources, it is impossible for them to continue because they are waiting for the resources owned by each other's threads.

The P2 process has R1 resources, but he is asking for R2 resources, while the P1 process has R2 resources, but he is requesting R1 resources.

1.1 Coffman conditions--4 conditions for generating a deadlock

If the following 4 scenarios exist in a system, the chance of a deadlock situation will rise

    • Mutex condition: A process requires an exclusive control over the assigned resource, that is, a resource is occupied by only one process over a period of time
    • Wait and hold conditions: when a process is blocked by a request for resources, the resources that have been obtained are left
    • Inalienable condition : The resources that the process has obtained are not deprived until they are used, and can only be released by themselves when they are exhausted.
    • Loop wait Condition: in the event of a deadlock, there must be a process-a circular chain of resources . More generally, there will be process collections {p1,p2,p3 .... PN},P1 Apply for P2 resources, P2 apply for P3 resources .... The PN application P1 the acquired resources, thus forming a closed loop.

These 4 conditions, the Coffman condition, were first proposed by Edward G.coffman, Mr. Jr, in 1971.

Second, Java Multi-threaded deadlock detection

Starting from JDK1.5 The package provides the Threadmxbean class, which can be used to obtain a wide variety of information about the thread, including the deadlock of the probe thread. The Findmonitordeadlockedthreads () method returns long[], which represents the ID of the thread in which the deadlock occurred. If the long[] array equals null, there is no thread that found the deadlock. But this method only monitors the deadlock of Object Monitor, and Ownable Synchronizer with the Java.util.concurrent package is powerless. For this JDK1.6 introduced a new method Finddeadlockedthreads () In addition to monitoring the object monitor deadlock, but also monitoring ownable synchronizer deadlock.

The problem of thread deadlock detection can be resolved by establishing a recurring task that allows it to use Threadmxbean to periodically check for the presence of deadlock threads. For example:

 Public classThreaddeadlockdetector {//set up scheduler for periodic tasks    Private FinalTimer Threadcheck =NewTimer ("Threaddeadlockdector",true); Private Finalcollection<listener> listeners =NewCopyonwritearrayset<listener>(); Private FinalThreadmxbean Mbean =Managementfactory.getthreadmxbean (); Private Static Final intDefault_deadlock_check_period = 10000;  PublicThreaddeadlockdetector () { This(Default_deadlock_check_period); }         PublicThreaddeadlockdetector (intdeadlockcheckperiod) {        //establish a mandate for periodic verificationThreadcheck.schedule (NewTimerTask () {@Override Public voidrun () {checkfordeadlocks (); }                    }, 10, Deadlockcheckperiod); }        //A deadlock alarm is issued once the existing deadlock is returned    Private voidcheckfordeadlocks () {Long[] IDs =finddeadlockedthreads (); if(IDs! =NULL&& ids.length > 0) {thread[] threads=NewThread[ids.length];  for(inti=0; i<threads.length; i++) {Threads[i]=Findmatchingthread (Mbean.getthreadinfo (ids[i));        } firedeadlockdetected (threads); }            }        //verifying that there is a deadlock    Private Long[] Finddeadlockedthreads () {if(mbean.issynchronizerusagesupported ()) {returnmbean.finddeadlockedthreads (); }Else{            returnmbean.findmonitordeadlockedthreads (); }    }        PrivateThread findmatchingthread (threadinfo inf) { for(Thread thread:Thread.getAllStackTraces (). KeySet ()) {if(Thread.getid () = =Inf.getthreadid ()) {                returnthread; }        }                Throw NewIllegalStateException ("deadlocked Thread not Found"); }         Public BooleanAddListener (Listener l) {returnListeners.add (L); }         Public BooleanRemoveListener (Listener l) {returnListeners.remove (L); }        Private voidfiredeadlockdetected (thread[] threads) { for(Listener l:listeners) {l.deallockdetected (threads); }    }         Public InterfaceListener {voiddeallockdetected (thread[] deadlockedthreads); }}

Java Thread-deadlock (deadlock)

Related Article

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: 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.