<p>When writing multi-threaded applications, one of the most common problems experienced are deadlocks.  </p>

<p>My questions to the community are:</p>

<ol>
<li><p>What is a deadlock? </p></li>
<li><p>How do you detect them? </p></li>
<li><p>Do you handle them?  </p></li>
<li><p>And finally, how do you prevent them from occurring?</p></li>
</ol>

[{'answer_id': 34520, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 9, 'selected': True, 'text': "<p>A <strong>lock</strong> occurs when multiple processes try to access the same resource at the same time.</p>\n\n<p>One process loses out and must wait for the other to finish.</p>\n\n<p>A <strong>deadlock</strong> occurs when the waiting process is still holding on to another resource that the first needs before it can finish.</p>\n\n<p>So, an example:</p>\n\n<p>Resource A and resource B are used by process X and process Y</p>\n\n<ul>\n<li>X starts to use A.</li>\n<li>X and Y try to start using B</li>\n<li>Y 'wins' and gets B first</li>\n<li>now Y needs to use A</li>\n<li>A is locked by X, which is waiting for Y</li>\n</ul>\n\n<p>The best way to avoid deadlocks is to avoid having processes cross over in this way. Reduce the need to lock anything as much as you can.</p>\n\n<p>In databases avoid making lots of changes to different tables in a single transaction, avoid triggers and switch to optimistic/dirty/nolock reads as much as possible.</p>\n"}, {'answer_id': 34522, 'author': 'Joseph Sturtevant', 'author_id': 317, 'author_profile': 'https://Stackoverflow.com/users/317', 'pm_score': 2, 'selected': False, 'text': '<p>Deadlock occurs when two threads aquire locks which prevent either of them from progressing. The best way to avoid them is with careful development. Many embedded systems protect against them by using a watchdog timer (a timer which resets the system whenever if it hangs for a certain period of time).</p>\n'}, {'answer_id': 34546, 'author': '17 of 26', 'author_id': 2284, 'author_profile': 'https://Stackoverflow.com/users/2284', 'pm_score': 4, 'selected': False, 'text': '<p>A deadlock happens when a thread is waiting for something that never occurs.</p>\n\n<p>Typically, it happens when a thread is waiting on a mutex or semaphore that was never released by the previous owner.</p>\n\n<p>It also frequently happens when you have a situation involving two threads and two locks like this:</p>\n\n<pre><code>Thread 1               Thread 2\n\nLock1-&gt;Lock();         Lock2-&gt;Lock();\nWaitForLock2();        WaitForLock1();   &lt;-- Oops!\n</code></pre>\n\n<p>You generally detect them because things that you expect to happen never do, or the application hangs entirely.</p>\n'}, {'answer_id': 34603, 'author': 'Mats Fredriksson', 'author_id': 2973, 'author_profile': 'https://Stackoverflow.com/users/2973', 'pm_score': 5, 'selected': False, 'text': '<p>Deadlocks will only occur when you have two or more locks that can be aquired at the same time and they are grabbed in different order.</p>\n\n<p>Ways to avoid having deadlocks are:</p>\n\n<ul>\n<li>avoid having locks (if possible), </li>\n<li>avoid having more than one lock</li>\n<li>always take the locks in the same order.</li>\n</ul>\n'}, {'answer_id': 40597, 'author': 'mweerden', 'author_id': 4285, 'author_profile': 'https://Stackoverflow.com/users/4285', 'pm_score': 0, 'selected': False, 'text': "<p>A deadlock is a state of a system in which no single process/thread is capable of executing an action. As mentioned by others, a deadlock is typically the result of a situation where each process/thread wishes to acquire a lock to a resource that is already locked by another (or even the same) process/thread.</p>\n\n<p>There are various methods to find them and avoid them. One is thinking very hard and/or trying lots of things. However, dealing with parallelism is notoriously difficult and most (if not all) people will not be able to completely avoid problems.</p>\n\n<p>Some more formal methods can be useful if you are serious about dealing with these kinds of issues. The most practical method that I'm aware of is to use the process theoretic approach. Here you model your system in some process language (e.g. CCS, CSP, ACP, mCRL2, LOTOS) and use the available tools to (model-)check for deadlocks (and perhaps some other properties as well). Examples of toolset to use are FDR, mCRL2, CADP and Uppaal. Some brave souls might even prove their systems deadlock free by using purely symbolic methods (theorem proving; look for Owicki-Gries).</p>\n\n<p>However, these formal methods typically do require some effort (e.g. learning the basics of process theory). But I guess that's simply a consequence of the fact that these problems are hard.</p>\n"}, {'answer_id': 18998026, 'author': 'onmyway133', 'author_id': 1418457, 'author_profile': 'https://Stackoverflow.com/users/1418457', 'pm_score': 3, 'selected': False, 'text': '<p>You can take a look at this <a href="http://www.albahari.com/threading/part2.aspx" rel="noreferrer">wonderful articles</a>, under section <strong>Deadlock</strong>. It is in C# but the idea is still the same for other platform. I quote here for easy reading</p>\n\n<blockquote>\n  <p>A deadlock happens when two threads each wait for a resource held by\n  the other, so neither can proceed. The easiest way to illustrate this\n  is with two locks:</p>\n</blockquote>\n\n<pre><code>object locker1 = new object();\nobject locker2 = new object();\n\nnew Thread (() =&gt; {\n                    lock (locker1)\n                    {\n                      Thread.Sleep (1000);\n                      lock (locker2);      // Deadlock\n                    }\n                  }).Start();\nlock (locker2)\n{\n  Thread.Sleep (1000);\n  lock (locker1);                          // Deadlock\n}\n</code></pre>\n'}, {'answer_id': 19850789, 'author': 'Marcus Thornton', 'author_id': 2288882, 'author_profile': 'https://Stackoverflow.com/users/2288882', 'pm_score': -1, 'selected': False, 'text': '<p>Mutex in essence is a lock, providing protected access to shared resources. Under Linux, the thread mutex data type is pthread_mutex_t. Before use, initialize it.</p>\n\n<p>To access to shared resources, you have to lock on the mutex. If the mutex already on the lock, the call will block the thread until the mutex is unlocked. Upon completion of the visit to shared resources, you have to unlock them.</p>\n\n<p>Overall, there are a few unwritten basic principles:</p>\n\n<ul>\n<li><p>Obtain the lock before using the shared resources.</p></li>\n<li><p>Holding the lock as short time as possible.</p></li>\n<li><p>Release the lock if the thread returns an error.</p></li>\n</ul>\n'}, {'answer_id': 21520435, 'author': 'user207421', 'author_id': 207421, 'author_profile': 'https://Stackoverflow.com/users/207421', 'pm_score': 2, 'selected': False, 'text': '<p>A deadlock occurs when there is a circular chain of threads or processes which each hold a locked resource and are trying to lock a resource held by the next element in the chain. For example, two threads that hold respectively lock A and lock B, and are both trying to acquire the other lock.</p>\n'}, {'answer_id': 29730813, 'author': 'puja bharti', 'author_id': 4807080, 'author_profile': 'https://Stackoverflow.com/users/4807080', 'pm_score': 0, 'selected': False, 'text': '<p>Deadlock is a situation occurs when there is less number of available resources as it is requested by the different process. It means that when the number of available resources become less than it is requested by the user then at that time the process goes in waiting condition .Some times waiting increases more and there is not any chance to check out the problem of lackness of resources then this situation is known as deadlock .\n                   Actually, deadlock is a major problem for us and it occurs only in multitasking operating system .deadlock can not occur in single tasking operating system because all the resources are present only for that task which is currently running......</p>\n'}, {'answer_id': 30101507, 'author': 'Varun', 'author_id': 3454208, 'author_profile': 'https://Stackoverflow.com/users/3454208', 'pm_score': 5, 'selected': False, 'text': '<p>To define deadlock, first I would define process.</p>\n\n<p><strong>Process</strong> <strong>:</strong> As we know process is nothing but a <code>program</code> in execution.</p>\n\n<p><strong>Resource</strong> <strong>:</strong> To execute a program process needs some resources. Resource categories may include memory, printers, CPUs, open files, tape drives, CD-ROMS, etc.</p>\n\n<p><strong>Deadlock</strong> <strong>:</strong> Deadlock is a situation or condition when two or more processes are holding some resources and trying to acquire some more resources, and they can not release the resources until they finish there execution.</p>\n\n<p><strong>Deadlock condition or situation</strong></p>\n\n<p><img src="https://i.stack.imgur.com/DDuIL.png" alt="enter image description here"></p>\n\n<p>In the above diagram there are two process <strong>P1</strong> and <strong>p2</strong> and there are two resources <strong>R1</strong> and <strong>R2</strong>.</p>\n\n<p>Resource <strong>R1</strong> is allocated to process <strong>P1</strong> and resource <strong>R2</strong> is allocated to process <strong>p2</strong>.\nTo complete execution of process <strong>P1</strong> needs resource <strong>R2</strong>, so <strong>P1</strong> request for <strong>R2</strong>, but <strong>R2</strong> is already allocated to <strong>P2</strong>.</p>\n\n<p>In the same way  Process <strong>P2</strong> to complete its execution needs <strong>R1</strong>, but <strong>R1</strong> is already allocated to <strong>P1</strong>.</p>\n\n<p>both the processes can not release their resource until and unless they complete their execution. So both are waiting for another resources and they will wait forever. So this is a <strong>DEADLOCK</strong> Condition.</p>\n\n<p>In order for deadlock to occur, four conditions must be true.</p>\n\n<ol>\n<li><strong>Mutual exclusion</strong> - Each resource is either currently allocated to exactly one process or it is available. (Two processes cannot\nsimultaneously control the same resource or be in their critical\nsection).</li>\n<li><strong>Hold and Wait</strong> - processes currently holding resources can request new resources.</li>\n<li><strong>No preemption</strong> - Once a process holds a resource, it cannot be taken away by another process or the kernel.</li>\n<li><strong>Circular wait</strong> - Each process is waiting to obtain a resource which is held by another process.</li>\n</ol>\n\n<p>and all these condition are satisfied in above diagram.</p>\n'}, {'answer_id': 35209902, 'author': 'Rohit Singh', 'author_id': 4700156, 'author_profile': 'https://Stackoverflow.com/users/4700156', 'pm_score': 2, 'selected': False, 'text': "<p>Deadlock is a common problem in multiprocessing/multiprogramming problems in OS.\nSay there are two processes P1, P2 and two globally shareable resource R1, R2 and in critical section both resources need to be accessed </p>\n\n<p>Initially, the OS assigns R1 to process P1 and R2 to process P2.\nAs both processes are running concurrently they may start executing their code but the PROBLEM arises when a process hits the critical section.\nSo process R1 will wait for process P2 to release R2 and vice versa...\nSo they will wait for forever (DEADLOCK CONDITION).         </p>\n\n<p>A small ANALOGY...  </p>\n\n<blockquote>\n  <p>Your Mother(OS),<br>\n  You(P1),<br>\n  Your brother(P2),<br>\n  Apple(R1),<br>\n  Knife(R2),<br>\n  critical section(cutting apple with knife).    </p>\n  \n  <p>Your mother gives you the apple and the knife to your brother in the beginning.<br>\n  Both are happy and playing(Executing their codes).<br>\n  Anyone of you wants to cut the apple(critical section) at some point.<br>\n  You don't want to give the apple to your brother.<br>\n  Your brother doesn't want to give the knife to you.<br>\n  So both of you are going to wait for a long very long time :)</p>\n</blockquote>\n"}, {'answer_id': 35640575, 'author': 'Levent Divilioglu', 'author_id': 3128926, 'author_profile': 'https://Stackoverflow.com/users/3128926', 'pm_score': 7, 'selected': False, 'text': '<p>Let me explain a real world (not actually real) example for a deadlock situation from the crime movies. Imagine a criminal holds an hostage and against that, a cop also holds an hostage who is a friend of the criminal. In this case, criminal is not going to let the hostage go if cop won\'t let his friend to let go. Also the cop is not going to let the friend of criminal let go, unless the criminal releases the hostage. This is an endless untrustworthy situation, because both sides are insisting the first step from each other.</p>\n\n<h3>Criminal & Cop Scene</h3>\n\n<p><a href="https://i.stack.imgur.com/3XVzK.png"><img src="https://i.stack.imgur.com/3XVzK.png" alt="enter image description here"></a></p>\n\n<p>So simply, when two threads needs two different resources and each of them has the lock of the resource that the other need, it is a deadlock.</p>\n\n<h3>Another High Level Explanation of Deadlock : Broken Hearts</h3>\n\n<p>You are dating with a girl and one day after an argument, both sides are heart-broken to each other and waiting for an <strong>I-am-sorry-and-I-missed-you</strong> call. In this situation, both sides want to communicate each other if and only if one of them receives an <strong>I-am-sorry</strong> call from the other. Because that neither of each is going to start communication and waiting in a passive state, both will wait for the other to start communication which ends up in a deadlock situation.</p>\n'}, {'answer_id': 43426875, 'author': 'Sapna', 'author_id': 7623176, 'author_profile': 'https://Stackoverflow.com/users/7623176', 'pm_score': 0, 'selected': False, 'text': '<p>Above some explanations are nice. Hope this may also useful:\n<a href="https://ora-data.blogspot.in/2017/04/deadlock-in-oracle.html" rel="nofollow noreferrer">https://ora-data.blogspot.in/2017/04/deadlock-in-oracle.html</a></p>\n\n<p>In a database, when a session (e.g. ora) wants a resource held by another session (e.g. data), but that session (data) also wants a resource which is held by the first session (ora). There can be more than 2 sessions involved also but idea will be the same.\nActually, Deadlocks prevent some transactions from continuing to work.\nFor example:\nSuppose, ORA-DATA holds lock A and requests lock B\nAnd SKU holds lock B and requests lock A.</p>\n\n<p>Thanks,</p>\n'}, {'answer_id': 50011904, 'author': 'Arun Raaj', 'author_id': 4334162, 'author_profile': 'https://Stackoverflow.com/users/4334162', 'pm_score': 0, 'selected': False, 'text': '<p>Deadlock occurs when a thread is waiting for other thread to finish and vice versa.   </p>\n\n<p><strong>How to avoid?</strong><br>\n                 - Avoid Nested Locks<br>\n - Avoid Unnecessary Locks<br>\n - Use thread join()</p>\n\n<p><strong>How do you detect it?</strong><br>\nrun this command in cmd:  </p>\n\n<pre><code>jcmd $PID Thread.print\n</code></pre>\n\n<p><a href="https://www.geeksforgeeks.org/deadlock-in-java-multithreading/" rel="nofollow noreferrer">reference</a> : geeksforgeeks</p>\n'}, {'answer_id': 51961244, 'author': 'Vivek Pratap Singh', 'author_id': 3758710, 'author_profile': 'https://Stackoverflow.com/users/3758710', 'pm_score': 1, 'selected': False, 'text': '<p>A classic and very simple program for understanding <strong>Deadlock</strong> situation :-</p>\n\n<pre><code>public class Lazy {\n\n    private static boolean initialized = false;\n\n    static {\n        Thread t = new Thread(new Runnable() {\n            public void run() {\n                initialized = true;\n            }\n        });\n\n        t.start();\n\n        try {\n            t.join();\n        } catch (InterruptedException e) {\n            e.printStackTrace();\n        }\n    }\n\n    public static void main(String[] args) {\n        System.out.println(initialized);\n    }\n}\n</code></pre>\n\n<p>When the main thread invokes Lazy.main, it checks whether the class Lazy\nhas been initialized and begins to initialize the class. The\nmain thread now sets initialized to false , creates and starts a background\nthread whose run method sets initialized to true , and waits for the background thread to complete.</p>\n\n<p>This time, the class is currently being initialized by another thread.\nUnder these circumstances, the current thread, which is the background thread,\nwaits on the Class object until initialization is complete. Unfortunately, the thread\nthat is doing the initialization, the main thread, is waiting for the background\nthread to complete. Because the two threads are now waiting for each other, the\nprogram is <strong>DEADLOCKED.</strong></p>\n'}, {'answer_id': 57700889, 'author': 'Raghav Navada', 'author_id': 612581, 'author_profile': 'https://Stackoverflow.com/users/612581', 'pm_score': 0, 'selected': False, 'text': "<p>Deadlocks does not just occur with locks, although that's the most frequent cause. In C++, you can create deadlock with two threads and no locks by just having each thread call join() on the std::thread object for the other.  </p>\n"}, {'answer_id': 58605921, 'author': 'Vlad Mihalcea', 'author_id': 1025118, 'author_profile': 'https://Stackoverflow.com/users/1025118', 'pm_score': 2, 'selected': False, 'text': '<h2>Lock-based concurrency control</h2>\n<p>Using locking for controlling access to shared resources is prone to deadlocks, and the transaction scheduler alone cannot prevent their occurrences.</p>\n<p>For instance, relational database systems use various locks to guarantee transaction <a href="https://vladmihalcea.com/a-beginners-guide-to-acid-and-database-transactions/" rel="nofollow noreferrer"><code>ACID</code></a> properties.</p>\n<p>No matter what relational database system you are using, locks will always be acquired when modifying (e.g., <code>UPDATE</code> or <code>DELETE</code>) a certain table record. Without locking a row that was modified by a currently running transaction, <code>Atomicity</code> would be compromised).</p>\n<h2>What is a deadlock</h2>\n<p>A deadlock happens when two concurrent transactions cannot make progress because each one waits for the other to release a lock, as illustrated in the following diagram.</p>\n<p><a href="https://vladmihalcea.com/database-deadlock/" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Glwqs.png" alt="Deadlock" /></a></p>\n<p>Because both transactions are in the lock acquisition phase, neither one releases a lock prior to acquiring the next one.</p>\n<h2>Recovering from a deadlock situation</h2>\n<p>If you\'re using a Concurrency Control algorithm that relies on locks, then there is always the risk of running into a deadlock situation. Deadlocks can occur in any concurrency environment, not just in a database system.</p>\n<p>For instance, a multithreading program can deadlock if two or more threads are waiting on locks that were previously acquired so that no thread can make any progress. If this happens in a Java application, the JVM cannot just force a Thread to stop its execution and release its locks.</p>\n<p>Even if the <code>Thread</code> class exposes a <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#stop--" rel="nofollow noreferrer"><code>stop</code></a> method, that method has been deprecated since Java 1.1 because it can cause objects to be left in an inconsistent state after a thread is stopped. Instead, Java defines an <code>interrupt</code> method, which acts as a hint as a thread that gets interrupted can simply ignore the interruption and continue its execution.</p>\n<p>For this reason, a Java application cannot recover from a deadlock situation, and it is the responsibility of the application developer to order the lock acquisition requests in such a way that deadlocks can never occur.</p>\n<p>However, a database system cannot enforce a given lock acquisition order since it\'s impossible to foresee what other locks a certain transaction will want to acquire further. Preserving the lock order becomes the responsibility of the data access layer, and the database can only assist in recovering from a deadlock situation.</p>\n<p>The database engine runs a separate process that scans the current conflict graph for lock-wait cycles (which are caused by deadlocks).\nWhen a cycle is detected, the database engine picks one transaction and aborts it, causing its locks to be released, so that the other transaction can make progress.</p>\n<p>Unlike the JVM, a database transaction is designed as an atomic unit of work. Hence, a rollback leaves the database in a consistent state.</p>\n'}, {'answer_id': 73669574, 'author': 'Yilmaz', 'author_id': 10262805, 'author_profile': 'https://Stackoverflow.com/users/10262805', 'pm_score': 0, 'selected': False, 'text': '<p>Let\'s say one thread wants to transfer money from &quot;A Account =&gt; B Account&quot; and another thread wants to transfer money from &quot;B Account =&gt; A Account&quot;, simultaneously. This can cause a <code>deadlock</code>.</p>\n<p>The first thread will take a lock on &quot;Account A&quot; and then it has to take a lock on &quot;Account B&quot; but it cannot because second thread will already took lock on &quot;Account B&quot;. Similarly second thread cannot take a lock on A Account because it is locked by the first thread. so this transaction will remain incomplete and our system will lose 2 threads. To prevent this, we can add a rule that locks the database records in sorted order. So thread should look at accounts name or IDs and decide to lock in a sorted order: A =&gt; B. There will be a race condition here and whoever wins, process its code and the second thread will take over. This is the solution for this specific case but deadlocks may occur in many reasons so each case will have a different solution.</p>\n<p>Os has a deadlock detection mechanism with a certain interval of time, and when it detects the deadlock, it starts a recovery approach. <a href="https://www.baeldung.com/cs/os-deadlock" rel="nofollow noreferrer">More on deadlock detection</a></p>\n<p>In the example we lost 2 threads but if we get more deadlocks, those deadlocks can bring down the system.</p>\n'}]
['https://Stackoverflow.com/questions/34512', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1931/']