<p>When writing multithreaded applications, one of the most common problems experienced is race conditions.</p>
<p>My questions to the community are:</p>
<ul>
<li>What is the race condition?</li>
<li>How do you detect them?</li>
<li>How do you handle them?</li>
<li>Finally, how do you prevent them from occurring?</li>
</ul>

[{'answer_id': 34537, 'author': 'Steve Gury', 'author_id': 1578, 'author_profile': 'https://Stackoverflow.com/users/1578', 'pm_score': 5, 'selected': False, 'text': '<p>A race condition is a kind of bug, that happens only with certain temporal conditions.</p>\n\n<p>Example:\nImagine you have two threads, A and B.</p>\n\n<p>In Thread A:</p>\n\n<pre class="lang-c prettyprint-override"><code>if( object.a != 0 )\n    object.avg = total / object.a\n</code></pre>\n\n<p>In Thread B:</p>\n\n<pre class="lang-c prettyprint-override"><code>object.a = 0\n</code></pre>\n\n<p>If thread A is preempted just after having check that object.a is not null, B will do <code>a = 0</code>, and when thread A will gain the processor, it will do a "divide by zero". </p>\n\n<p>This bug only happen when thread A is preempted just after the if statement, it\'s very rare, but it can happen.</p>\n'}, {'answer_id': 34550, 'author': 'Lehane', 'author_id': 142, 'author_profile': 'https://Stackoverflow.com/users/142', 'pm_score': 12, 'selected': True, 'text': '<p>A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, you don\'t know the order in which the threads will attempt to access the shared data. Therefore, the result of the change in data is dependent on the thread scheduling algorithm, i.e. both threads are "racing" to access/change the data. </p>\n\n<p>Problems often occur when one thread does a "check-then-act" (e.g. "check" if the value is X, then "act" to do something that depends on the value being X) and another thread does something to the value in between the "check" and the "act". E.g:</p>\n\n<pre><code>if (x == 5) // The "Check"\n{\n   y = x * 2; // The "Act"\n\n   // If another thread changed x in between "if (x == 5)" and "y = x * 2" above,\n   // y will not be equal to 10.\n}\n</code></pre>\n\n<p>The point being, y could be 10, or it could be anything, depending on whether another thread changed x in between the check and act. You have no real way of knowing.</p>\n\n<p>In order to prevent race conditions from occurring, you would typically put a lock around the shared data to ensure only one thread can access the data at a time. This would mean something like this:</p>\n\n<pre><code>// Obtain lock for x\nif (x == 5)\n{\n   y = x * 2; // Now, nothing can change x until the lock is released. \n              // Therefore y = 10\n}\n// release lock for x\n</code></pre>\n'}, {'answer_id': 34562, 'author': 'Jorge Córdoba', 'author_id': 2695, 'author_profile': 'https://Stackoverflow.com/users/2695', 'pm_score': 5, 'selected': False, 'text': '<p>A race condition is a situation on concurrent programming where two concurrent threads or processes compete for a resource and the resulting final state depends on who gets the resource first.</p>\n'}, {'answer_id': 34578, 'author': 'tsellon', 'author_id': 3575, 'author_profile': 'https://Stackoverflow.com/users/3575', 'pm_score': 4, 'selected': False, 'text': "<p>Race conditions occur in multi-threaded applications or multi-process systems.  A race condition, at its most basic, is anything that makes the assumption that two things not in the same thread or process will happen in a particular order, without taking steps to ensure that they do.  This happens commonly when two threads are passing messages by setting and checking member variables of a class both can access.  There's almost always a race condition when one thread calls sleep to give another thread time to finish a task (unless that sleep is in a loop, with some checking mechanism).</p>\n\n<p>Tools for preventing race conditions are dependent on the language and OS, but some comon ones are mutexes, critical sections, and signals.  Mutexes are good when you want to make sure you're the only one doing something.  Signals are good when you want to make sure someone else has finished doing something.  Minimizing shared resources can also help prevent unexpected behaviors</p>\n\n<p>Detecting race conditions can be difficult, but there are a couple signs.  Code which relies heavily on sleeps is prone to race conditions, so first check for calls to sleep in the affected code.  Adding particularly long sleeps can also be used for debugging to try and force a particular order of events.  This can be useful for reproducing the behavior, seeing if you can make it disappear by changing the timing of things, and for testing solutions put in place.  The sleeps should be removed after debugging.</p>\n\n<p>The signature sign that one has a race condition though, is if there's an issue that only occurs intermittently on some machines.  Common bugs would be crashes and deadlocks.  With logging, you should be able to find the affected area and work back from there.</p>\n"}, {'answer_id': 34621, 'author': 'Chris Conway', 'author_id': 1412, 'author_profile': 'https://Stackoverflow.com/users/1412', 'pm_score': 5, 'selected': False, 'text': '<p>A sort-of-canonical definition is "<em>when two threads access the same location in memory at the same time, and at least one of the accesses is a write</em>." In the situation the "reader" thread may get the old value or the new value, depending on which thread "wins the race." This is not always a bug&mdash;in fact, some really hairy low-level algorithms do this on purpose&mdash;but it should generally be avoided. @Steve Gury give\'s a good example of when it might be a problem.</p>\n'}, {'answer_id': 34745, 'author': 'privatehuff', 'author_id': 2570347, 'author_profile': 'https://Stackoverflow.com/users/2570347', 'pm_score': 8, 'selected': False, 'text': '<p>A "race condition" exists when multithreaded (or otherwise parallel) code that would access a shared resource could do so in such a way as to cause unexpected results.</p>\n\n<p>Take this example:</p>\n\n<pre class="lang-c prettyprint-override"><code>for ( int i = 0; i &lt; 10000000; i++ )\n{\n   x = x + 1; \n}\n</code></pre>\n\n<p>If you had 5 threads executing this code at once, the value of x WOULD NOT end up being 50,000,000.  It would in fact vary with each run.</p>\n\n<p>This is because, in order for each thread to increment the value of x, they have to do the following: (simplified, obviously)</p>\n\n<pre>\nRetrieve the value of x\nAdd 1 to this value\nStore this value to x\n</pre>\n\n<p>Any thread can be at any step in this process at any time, and they can step on each other when a shared resource is involved.  The state of x can be changed by another thread during the time between x is being read and when it is written back.</p>\n\n<p>Let\'s say a thread retrieves the value of x, but hasn\'t stored it yet.  Another thread can also retrieve the <b>same</b> value of x (because no thread has changed it yet) and then they would both be storing the <b>same</b> value (x+1) back in x!</p>\n\n<p>Example:</p>\n\n<pre>\nThread 1: reads x, value is 7\nThread 1: add 1 to x, value is now 8\nThread 2: reads x, <b>value is 7</b>\nThread 1: stores 8 in x\nThread 2: adds 1 to x, value is now 8\nThread 2: <b>stores 8 in x</b>\n</pre>\n\n<p>Race conditions can be avoided by employing some sort of <b>locking</b> mechanism before the code that accesses the shared resource:</p>\n\n<pre class="lang-c prettyprint-override"><code>for ( int i = 0; i &lt; 10000000; i++ )\n{\n   //lock x\n   x = x + 1; \n   //unlock x\n}\n</code></pre>\n\n<p>Here, the answer comes out as 50,000,000 every time.</p>\n\n<p>For more on locking, search for: mutex, semaphore, critical section, shared resource.</p>\n'}, {'answer_id': 8222450, 'author': 'realPK', 'author_id': 853001, 'author_profile': 'https://Stackoverflow.com/users/853001', 'pm_score': 0, 'selected': False, 'text': '<p>Here is the classical Bank Account Balance example which will help newbies to understand Threads in Java easily w.r.t. race conditions:</p>\n\n<pre class="lang-java prettyprint-override"><code>public class BankAccount {\n\n/**\n * @param args\n */\nint accountNumber;\ndouble accountBalance;\n\npublic synchronized boolean Deposit(double amount){\n    double newAccountBalance=0;\n    if(amount&lt;=0){\n        return false;\n    }\n    else {\n        newAccountBalance = accountBalance+amount;\n        accountBalance=newAccountBalance;\n        return true;\n    }\n\n}\npublic synchronized boolean Withdraw(double amount){\n    double newAccountBalance=0;\n    if(amount&gt;accountBalance){\n        return false;\n    }\n    else{\n        newAccountBalance = accountBalance-amount;\n        accountBalance=newAccountBalance;\n        return true;\n    }\n}\n\npublic static void main(String[] args) {\n    // TODO Auto-generated method stub\n    BankAccount b = new BankAccount();\n    b.accountBalance=2000;\n    System.out.println(b.Withdraw(3000));\n\n}\n</code></pre>\n'}, {'answer_id': 12420366, 'author': 'Konstantin Dinev', 'author_id': 1348324, 'author_profile': 'https://Stackoverflow.com/users/1348324', 'pm_score': 4, 'selected': False, 'text': '<p>Microsoft actually have published a really detailed <a href="http://support.microsoft.com/kb/317723" rel="noreferrer">article</a> on this matter of race conditions and deadlocks. The most summarized abstract from it would be the title paragraph:</p>\n\n<blockquote>\n  <p>A race condition occurs when two threads access a shared variable at\n  the same time. The first thread reads the variable, and the second\n  thread reads the same value from the variable. Then the first thread\n  and second thread perform their operations on the value, and they race\n  to see which thread can write the value last to the shared variable.\n  The value of the thread that writes its value last is preserved,\n  because the thread is writing over the value that the previous thread\n  wrote.</p>\n</blockquote>\n'}, {'answer_id': 16861236, 'author': 'Morsu', 'author_id': 2440915, 'author_profile': 'https://Stackoverflow.com/users/2440915', 'pm_score': 0, 'selected': False, 'text': '<p>Try this basic example for better understanding of race condition:</p>\n\n<pre><code>    public class ThreadRaceCondition {\n\n    /**\n     * @param args\n     * @throws InterruptedException\n     */\n    public static void main(String[] args) throws InterruptedException {\n        Account myAccount = new Account(22222222);\n\n        // Expected deposit: 250\n        for (int i = 0; i &lt; 50; i++) {\n            Transaction t = new Transaction(myAccount,\n                    Transaction.TransactionType.DEPOSIT, 5.00);\n            t.start();\n        }\n\n        // Expected withdrawal: 50\n        for (int i = 0; i &lt; 50; i++) {\n            Transaction t = new Transaction(myAccount,\n                    Transaction.TransactionType.WITHDRAW, 1.00);\n            t.start();\n\n        }\n\n        // Temporary sleep to ensure all threads are completed. Don\'t use in\n        // realworld :-)\n        Thread.sleep(1000);\n        // Expected account balance is 200\n        System.out.println("Final Account Balance: "\n                + myAccount.getAccountBalance());\n\n    }\n\n}\n\nclass Transaction extends Thread {\n\n    public static enum TransactionType {\n        DEPOSIT(1), WITHDRAW(2);\n\n        private int value;\n\n        private TransactionType(int value) {\n            this.value = value;\n        }\n\n        public int getValue() {\n            return value;\n        }\n    };\n\n    private TransactionType transactionType;\n    private Account account;\n    private double amount;\n\n    /*\n     * If transactionType == 1, deposit else if transactionType == 2 withdraw\n     */\n    public Transaction(Account account, TransactionType transactionType,\n            double amount) {\n        this.transactionType = transactionType;\n        this.account = account;\n        this.amount = amount;\n    }\n\n    public void run() {\n        switch (this.transactionType) {\n        case DEPOSIT:\n            deposit();\n            printBalance();\n            break;\n        case WITHDRAW:\n            withdraw();\n            printBalance();\n            break;\n        default:\n            System.out.println("NOT A VALID TRANSACTION");\n        }\n        ;\n    }\n\n    public void deposit() {\n        this.account.deposit(this.amount);\n    }\n\n    public void withdraw() {\n        this.account.withdraw(amount);\n    }\n\n    public void printBalance() {\n        System.out.println(Thread.currentThread().getName()\n                + " : TransactionType: " + this.transactionType + ", Amount: "\n                + this.amount);\n        System.out.println("Account Balance: "\n                + this.account.getAccountBalance());\n    }\n}\n\nclass Account {\n    private int accountNumber;\n    private double accountBalance;\n\n    public int getAccountNumber() {\n        return accountNumber;\n    }\n\n    public double getAccountBalance() {\n        return accountBalance;\n    }\n\n    public Account(int accountNumber) {\n        this.accountNumber = accountNumber;\n    }\n\n    // If this method is not synchronized, you will see race condition on\n    // Remove syncronized keyword to see race condition\n    public synchronized boolean deposit(double amount) {\n        if (amount &lt; 0) {\n            return false;\n        } else {\n            accountBalance = accountBalance + amount;\n            return true;\n        }\n    }\n\n    // If this method is not synchronized, you will see race condition on\n    // Remove syncronized keyword to see race condition\n    public synchronized boolean withdraw(double amount) {\n        if (amount &gt; accountBalance) {\n            return false;\n        } else {\n            accountBalance = accountBalance - amount;\n            return true;\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 18506177, 'author': 'Baris Kasikci', 'author_id': 1631712, 'author_profile': 'https://Stackoverflow.com/users/1631712', 'pm_score': 6, 'selected': False, 'text': '<p>There is an important technical difference between race conditions and data races. Most answers seem to make the assumption that these terms are equivalent, but they are not. </p>\n\n<p>A data race occurs when 2 instructions access the same memory location, at least one of these accesses is a write and there is no <em>happens before ordering</em> among these accesses. Now what constitutes a happens before ordering is subject to a lot of debate, but in general ulock-lock pairs on the same lock variable and wait-signal pairs on the same condition variable induce a happens-before order. </p>\n\n<p>A race condition is a semantic error. It is a flaw that occurs in the timing or the ordering of events that leads to erroneous program <em>behavior</em>. </p>\n\n<p>Many race conditions can be (and in fact are) caused by data races, but this is not necessary. As a matter of fact, data races and race conditions are neither the necessary, nor the sufficient condition for one another. <a href="http://blog.regehr.org/archives/490" rel="noreferrer">This</a> blog post also explains the difference very well, with a simple bank transaction example. Here is another simple <a href="https://stackoverflow.com/questions/11276259/are-data-races-and-race-condition-actually-the-same-thing-in-context-of-conc/18049303#18049303">example</a> that explains the difference.</p>\n\n<p>Now that we nailed down the terminology, let us try to answer the original question.</p>\n\n<p>Given that race conditions are semantic bugs, there is no general way of detecting them. This is because there is no way of having an automated oracle that can distinguish correct vs. incorrect program behavior in the general case. Race detection is an undecidable problem.</p>\n\n<p>On the other hand, data races have a precise definition that does not necessarily relate to correctness, and therefore one can detect them. There are many flavors of data race detectors (static/dynamic data race detection, lockset-based data race detection, happens-before based data race detection, hybrid data race detection). A state of the art dynamic data race detector is <a href="https://code.google.com/p/data-race-test/wiki/ThreadSanitizer" rel="noreferrer">ThreadSanitizer</a> which works very well in practice.</p>\n\n<p>Handling data races in general requires some programming discipline to induce happens-before edges between accesses to shared data (either during development, or once they are detected using the above mentioned tools). this can be done through locks, condition variables, semaphores, etc. However, one can also employ different programming paradigms like message passing (instead of shared memory) that avoid data races by construction.</p>\n'}, {'answer_id': 19190984, 'author': 'Vishal Shukla', 'author_id': 2734949, 'author_profile': 'https://Stackoverflow.com/users/2734949', 'pm_score': 8, 'selected': False, 'text': '<blockquote>\n  <p>What is a Race Condition?</p>\n</blockquote>\n\n<p>You are planning to go to a movie at 5 pm. You inquire about the availability of the tickets at 4 pm. The representative says that they are available. You relax and reach the ticket window 5 minutes before the show. I\'m sure you can guess what happens: it\'s a full house. The problem here was in the duration between the check and the action. You inquired at 4 and acted at 5. In the meantime, someone else grabbed the tickets. That\'s a race condition - specifically a "check-then-act" scenario of race conditions.</p>\n\n<blockquote>\n  <p>How do you detect them?</p>\n</blockquote>\n\n<p>Religious code review, multi-threaded unit tests. There is no shortcut. There are few Eclipse plugin emerging on this, but nothing stable yet.</p>\n\n<blockquote>\n  <p>How do you handle and prevent them?</p>\n</blockquote>\n\n<p>The best thing would be to create side-effect free and stateless functions, use immutables as much as possible. But that is not always possible. So using java.util.concurrent.atomic, concurrent data structures, proper synchronization, and actor based concurrency will help.</p>\n\n<p>The best resource for concurrency is JCIP. You can also get some more <a href="http://brevitaz.com/race-condition-java-concurrency-2/">details on above explanation here</a>.</p>\n'}, {'answer_id': 25708683, 'author': 'kiriloff', 'author_id': 1141493, 'author_profile': 'https://Stackoverflow.com/users/1141493', 'pm_score': 0, 'selected': False, 'text': '<p>You don\'t always want to discard a race condition. If you have a flag which can be read and written by multiple threads, and this flag is set to \'done\' by one thread so that other thread stop processing when flag is set to \'done\', you don\'t want that "race condition" to be eliminated. In fact, this one can be referred to as a benign race condition. </p>\n\n<p>However, using a tool for detection of race condition, it will be spotted as a harmful race condition.</p>\n\n<p>More details on race condition here, <a href="http://msdn.microsoft.com/en-us/magazine/cc546569.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/magazine/cc546569.aspx</a>. </p>\n'}, {'answer_id': 26931373, 'author': 'Adnan Qureshi', 'author_id': 1137271, 'author_profile': 'https://Stackoverflow.com/users/1137271', 'pm_score': 4, 'selected': False, 'text': '<blockquote>\n  <p>What is a race condition?</p>\n</blockquote>\n\n<p>The situation when the process is critically dependent on the sequence or timing of other events.</p>\n\n<p>For example,\nProcessor A and processor B <strong>both needs</strong> identical resource for their execution.</p>\n\n<blockquote>\n  <p>How do you detect them? </p>\n</blockquote>\n\n<p>There are tools to detect race condition automatically:</p>\n\n<ul>\n<li><a href="http://www.hpcaconf.org/hpca13/papers/014-zhou.pdf" rel="noreferrer">Lockset-Based Race Checker</a></li>\n<li><a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.39.9581&amp;rep=rep1&amp;type=pdf" rel="noreferrer">Happens-Before Race Detection</a></li>\n<li><a href="http://web.cs.msu.edu/~cse914/Readings/hybridDynamicRaceDetection-ppopp03.pdf" rel="noreferrer">Hybrid Race Detection</a></li>\n</ul>\n\n<blockquote>\n  <p>How do you handle them? </p>\n</blockquote>\n\n<p>Race condition can be handled by <strong>Mutex</strong> or <strong>Semaphores</strong>. They act as a lock allows a process to acquire a resource based on certain requirements to prevent race condition.</p>\n\n<blockquote>\n  <p>How do you prevent them from occurring?</p>\n</blockquote>\n\n<p>There are various ways to prevent race condition, such as <strong>Critical Section Avoidance</strong>.</p>\n\n<ol>\n<li>No two processes simultaneously inside their critical regions. (<strong>Mutual Exclusion)</strong></li>\n<li>No assumptions are made about speeds or the number of CPUs.</li>\n<li>No process running outside its critical region which blocks other processes.</li>\n<li>No process has to wait forever to enter its critical region. (A waits for B resources, B waits for C resources, C waits for A resources)</li>\n</ol>\n'}, {'answer_id': 31424696, 'author': 'bharanitharan', 'author_id': 358099, 'author_profile': 'https://Stackoverflow.com/users/358099', 'pm_score': 0, 'selected': False, 'text': '<p>Consider an operation which has to display the count as soon as the count gets incremented. ie., as soon as <strong>CounterThread</strong> increments the value <strong>DisplayThread</strong> needs to display the recently updated value.</p>\n\n<pre><code>int i = 0;\n</code></pre>\n\n<p>Output  </p>\n\n<pre><code>CounterThread -&gt; i = 1  \nDisplayThread -&gt; i = 1  \nCounterThread -&gt; i = 2  \nCounterThread -&gt; i = 3  \nCounterThread -&gt; i = 4  \nDisplayThread -&gt; i = 4\n</code></pre>\n\n<p>Here <strong>CounterThread</strong> gets the lock frequently and updates the value before <strong>DisplayThread</strong> displays it. Here exists a Race condition. Race Condition can be solved by using Synchronzation</p>\n'}, {'answer_id': 45498041, 'author': 'nybon', 'author_id': 84540, 'author_profile': 'https://Stackoverflow.com/users/84540', 'pm_score': 5, 'selected': False, 'text': '<p>Many answers in this discussion explains what a race condition is. I try to provide an explaination why this term is called <code>race condition</code> in software industry.</p>\n<h1>Why is it called <code>race condition</code>?</h1>\n<p>Race condition is not only related with software but also related with hardware too. Actually the term was initially coined by the hardware industry.</p>\n<p>According to <a href="https://en.wikipedia.org/wiki/Race_condition" rel="nofollow noreferrer">wikipedia</a>:</p>\n<blockquote>\n<p>The term originates with the idea of <strong>two signals racing each other</strong> to\n<strong>influence the output first</strong>.</p>\n<p>Race condition in a logic circuit:</p>\n<p><a href="https://i.stack.imgur.com/iUgaj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iUgaj.png" alt="enter image description here" /></a></p>\n</blockquote>\n<p>Software industry took this term without modification, which makes it a little bit difficult to understand.</p>\n<p>You need to do some replacement to map it to the software world:</p>\n<ul>\n<li>&quot;two signals&quot; ==&gt; &quot;two threads&quot;/&quot;two processes&quot;</li>\n<li>&quot;influence the output&quot; ==&gt; &quot;influence some shared state&quot;</li>\n</ul>\n<p>So race condition in software industry means &quot;two threads&quot;/&quot;two processes&quot; racing each other to &quot;influence some shared state&quot;, and the final result of the shared state will depend on some subtle timing difference, which could be caused by some specific thread/process launching order, thread/process scheduling, etc.</p>\n'}, {'answer_id': 45651528, 'author': 'Aleksei Moshkov', 'author_id': 5031817, 'author_profile': 'https://Stackoverflow.com/users/5031817', 'pm_score': 2, 'selected': False, 'text': '<p>You can <em>prevent race condition</em>, if you use "Atomic" classes. The reason is just the thread don\'t separate operation get and set, example is below:</p>\n\n<pre><code>AtomicInteger ai = new AtomicInteger(2);\nai.getAndAdd(5);\n</code></pre>\n\n<p>As a result, you will have 7 in link "ai". \nAlthough you did two actions, but the both operation confirm the same thread and no one other thread will interfere to this, that means no race conditions!   </p>\n'}, {'answer_id': 53626771, 'author': 'rashedcs', 'author_id': 6714430, 'author_profile': 'https://Stackoverflow.com/users/6714430', 'pm_score': 0, 'selected': False, 'text': '<p>A race condition is an undesirable situation that occurs when two or more process can access and change the shared data at the same time.It occurred because  there were conflicting accesses to a resource . Critical section problem may cause race condition. To solve critical condition among the process we have take out only one process at a time which execute the critical section.</p>\n'}, {'answer_id': 72158679, 'author': 'zacksiri', 'author_id': 1584262, 'author_profile': 'https://Stackoverflow.com/users/1584262', 'pm_score': 2, 'selected': False, 'text': '<p>I made a video that explains this.</p>\n<p>Essentially it is when you have a state with is shared across multiple threads and before the first execution on a given state is completed, another execution starts and the new thread’s initial state for a given operation is wrong because the previous execution has not completed.</p>\n<p>Because the initial state of the second execution is wrong, the resulting computation is also wrong. Because eventually the second execution will update the final state with the wrong result.</p>\n<p><a href="https://i.stack.imgur.com/rONSe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rONSe.png" alt="reading a shared state" /></a></p>\n<p><a href="https://i.stack.imgur.com/a9TgU.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/a9TgU.jpg" alt="final computation is incorrect" /></a></p>\n<p>You can view it here.\n<a href="https://youtu.be/RWRicNoWKOY" rel="nofollow noreferrer">https://youtu.be/RWRicNoWKOY</a></p>\n'}]
['https://Stackoverflow.com/questions/34510', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1931/']