<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Java Concurrency Examples – Code Walkthroughs &amp; Practical Tips</title>
	<atom:link href="https://www.programmertoolbox.com/tag/java-concurrency-examples/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.programmertoolbox.com/tag/java-concurrency-examples/</link>
	<description>Power up your programming</description>
	<lastBuildDate>Tue, 11 Nov 2025 18:40:10 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://www.programmertoolbox.com/wp-content/uploads/2025/10/icon-150x150.png</url>
	<title>Java Concurrency Examples – Code Walkthroughs &amp; Practical Tips</title>
	<link>https://www.programmertoolbox.com/tag/java-concurrency-examples/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Race Condition in Java Explained &#8211; With Real-World Examples</title>
		<link>https://www.programmertoolbox.com/race-condition-in-java-explained-with-real-world-examples/</link>
					<comments>https://www.programmertoolbox.com/race-condition-in-java-explained-with-real-world-examples/#respond</comments>
		
		<dc:creator><![CDATA[Geek Programmer]]></dc:creator>
		<pubDate>Tue, 28 Oct 2025 11:22:44 +0000</pubDate>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[atomic variables]]></category>
		<category><![CDATA[java concurrency examples]]></category>
		<category><![CDATA[multithreading bugs]]></category>
		<category><![CDATA[race condition in java]]></category>
		<category><![CDATA[synchronized vs lock]]></category>
		<category><![CDATA[thread safety]]></category>
		<guid isPermaLink="false">https://www.programmertoolbox.com/?p=243</guid>

					<description><![CDATA[<p>A race condition in Java occurs when two or more threads access shared data at the same time, leading to unpredictable results. In multithreaded Java applications, this can cause data corruption, inconsistent output, or even system crashes. Understanding how a race condition in Java happens — and how to prevent it — is essential for</p>
<p>The post <a href="https://www.programmertoolbox.com/race-condition-in-java-explained-with-real-world-examples/">Race Condition in Java Explained &#8211; With Real-World Examples</a> appeared first on <a href="https://www.programmertoolbox.com">Programmer Toolbox</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>A <strong>race condition in Java</strong> occurs when two or more threads access shared data at the same time, leading to unpredictable results. In multithreaded Java applications, this can cause data corruption, inconsistent output, or even system crashes. Understanding how a race condition in Java happens — and how to prevent it — is essential for writing thread-safe, reliable programs.</p>



<h2 class="wp-block-heading">Definition: What Is a Race Condition?</h2>



<p>A <strong>race condition</strong> occurs when the behavior of a program depends on the relative timing of events — such as the order in which threads are scheduled.<br>If two or more threads access and modify shared data simultaneously <strong>without proper coordination</strong>, the final result can vary between runs.</p>



<p>In short:</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>A race condition happens when “who gets there first” changes your program’s outcome.</p>
</blockquote>



<h2 class="wp-block-heading">Simple Java Example</h2>



<p>Let’s start with a simple case — incrementing a shared counter.</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2b2b2b;color:#c7c7c7">Java</span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>public class RaceConditionExample {
    private static int counter = 0;

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> increment());
        Thread t2 = new Thread(() -> increment());

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println("Final counter value: " + counter);
    }

    public static void increment() {
        for (int i = 0; i &lt; 100000; i++) {
            counter++;
        }
    }
}
</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #569CD6">public</span><span style="color: #D4D4D4"> </span><span style="color: #569CD6">class</span><span style="color: #D4D4D4"> </span><span style="color: #4EC9B0">RaceConditionExample</span><span style="color: #D4D4D4"> {</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #569CD6">private</span><span style="color: #D4D4D4"> </span><span style="color: #569CD6">static</span><span style="color: #D4D4D4"> </span><span style="color: #4EC9B0">int</span><span style="color: #D4D4D4"> </span><span style="color: #9CDCFE">counter</span><span style="color: #D4D4D4"> = </span><span style="color: #B5CEA8">0</span><span style="color: #D4D4D4">;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #569CD6">public</span><span style="color: #D4D4D4"> </span><span style="color: #569CD6">static</span><span style="color: #D4D4D4"> </span><span style="color: #4EC9B0">void</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">main</span><span style="color: #D4D4D4">(</span><span style="color: #4EC9B0">String</span><span style="color: #D4D4D4">[] </span><span style="color: #9CDCFE">args</span><span style="color: #D4D4D4">) </span><span style="color: #569CD6">throws</span><span style="color: #D4D4D4"> </span><span style="color: #4EC9B0">InterruptedException</span><span style="color: #D4D4D4"> {</span></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #4EC9B0">Thread</span><span style="color: #D4D4D4"> </span><span style="color: #9CDCFE">t1</span><span style="color: #D4D4D4"> = </span><span style="color: #C586C0">new</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">Thread</span><span style="color: #D4D4D4">(() </span><span style="color: #569CD6">-&gt;</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">increment</span><span style="color: #D4D4D4">());</span></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #4EC9B0">Thread</span><span style="color: #D4D4D4"> </span><span style="color: #9CDCFE">t2</span><span style="color: #D4D4D4"> = </span><span style="color: #C586C0">new</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">Thread</span><span style="color: #D4D4D4">(() </span><span style="color: #569CD6">-&gt;</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">increment</span><span style="color: #D4D4D4">());</span></span>
<span class="line"></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #9CDCFE">t1</span><span style="color: #D4D4D4">.</span><span style="color: #DCDCAA">start</span><span style="color: #D4D4D4">();</span></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #9CDCFE">t2</span><span style="color: #D4D4D4">.</span><span style="color: #DCDCAA">start</span><span style="color: #D4D4D4">();</span></span>
<span class="line"></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #9CDCFE">t1</span><span style="color: #D4D4D4">.</span><span style="color: #DCDCAA">join</span><span style="color: #D4D4D4">();</span></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #9CDCFE">t2</span><span style="color: #D4D4D4">.</span><span style="color: #DCDCAA">join</span><span style="color: #D4D4D4">();</span></span>
<span class="line"></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #9CDCFE">System</span><span style="color: #D4D4D4">.</span><span style="color: #9CDCFE">out</span><span style="color: #D4D4D4">.</span><span style="color: #DCDCAA">println</span><span style="color: #D4D4D4">(</span><span style="color: #CE9178">&quot;Final counter value: &quot;</span><span style="color: #D4D4D4"> + counter);</span></span>
<span class="line"><span style="color: #D4D4D4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #569CD6">public</span><span style="color: #D4D4D4"> </span><span style="color: #569CD6">static</span><span style="color: #D4D4D4"> </span><span style="color: #4EC9B0">void</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">increment</span><span style="color: #D4D4D4">() {</span></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #C586C0">for</span><span style="color: #D4D4D4"> (</span><span style="color: #4EC9B0">int</span><span style="color: #D4D4D4"> </span><span style="color: #9CDCFE">i</span><span style="color: #D4D4D4"> = </span><span style="color: #B5CEA8">0</span><span style="color: #D4D4D4">; i &lt; </span><span style="color: #B5CEA8">100000</span><span style="color: #D4D4D4">; i++) {</span></span>
<span class="line"><span style="color: #D4D4D4">            counter++;</span></span>
<span class="line"><span style="color: #D4D4D4">        }</span></span>
<span class="line"><span style="color: #D4D4D4">    }</span></span>
<span class="line"><span style="color: #D4D4D4">}</span></span>
<span class="line"></span></code></pre></div>



<p>You might expect the output to be <strong>200000</strong>, but often it’s <strong>less</strong>.<br>Why? Because both threads are updating the <code>counter</code> at the same time — one reads the value while the other is still writing it.<br>The two operations <strong>interleave</strong> unpredictably, corrupting the final result.</p>



<h2 class="wp-block-heading">Why Race Conditions Happen</h2>



<p>In Java (and most languages), the operation <code>counter++</code> is <strong>not atomic</strong>.<br>It actually performs three low-level steps:</p>



<ol class="wp-block-list">
<li>Read <code>counter</code> from memory</li>



<li>Add 1 to it</li>



<li>Write the new value back</li>
</ol>



<p>If Thread A reads the value at the same time Thread B writes it, one update can be lost — leading to incorrect results.</p>



<h2 class="wp-block-heading">Real-World Race Condition Scenarios</h2>



<p>Let’s look at a few real-world examples to make this more concrete.</p>



<h3 class="wp-block-heading">1. Banking System: Double Withdrawal</h3>



<p>Imagine two users withdrawing from the same bank account simultaneously:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2b2b2b;color:#c7c7c7">Java</span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>public class BankAccount {
    private int balance = 1000;

    public void withdraw(int amount) {
        if (balance >= amount) {
            balance -= amount;
        }
    }
}
</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #569CD6">public</span><span style="color: #D4D4D4"> </span><span style="color: #569CD6">class</span><span style="color: #D4D4D4"> </span><span style="color: #4EC9B0">BankAccount</span><span style="color: #D4D4D4"> {</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #569CD6">private</span><span style="color: #D4D4D4"> </span><span style="color: #4EC9B0">int</span><span style="color: #D4D4D4"> </span><span style="color: #9CDCFE">balance</span><span style="color: #D4D4D4"> = </span><span style="color: #B5CEA8">1000</span><span style="color: #D4D4D4">;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #569CD6">public</span><span style="color: #D4D4D4"> </span><span style="color: #4EC9B0">void</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">withdraw</span><span style="color: #D4D4D4">(</span><span style="color: #4EC9B0">int</span><span style="color: #D4D4D4"> </span><span style="color: #9CDCFE">amount</span><span style="color: #D4D4D4">) {</span></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #C586C0">if</span><span style="color: #D4D4D4"> (balance &gt;= amount) {</span></span>
<span class="line"><span style="color: #D4D4D4">            balance -= amount;</span></span>
<span class="line"><span style="color: #D4D4D4">        }</span></span>
<span class="line"><span style="color: #D4D4D4">    }</span></span>
<span class="line"><span style="color: #D4D4D4">}</span></span>
<span class="line"></span></code></pre></div>



<p>If two threads call <code>withdraw(800)</code> at the same time, both might pass the check <code>balance &gt;= amount</code> before either reduces it.<br>The result?<br>Final balance might become <strong>-600</strong>, even though that should never happen.</p>



<h3 class="wp-block-heading">2. E-Commerce: Double Purchase</h3>



<p>In an online store, two users may try to buy the <strong>last item in stock</strong> simultaneously.</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2b2b2b;color:#c7c7c7">Java</span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>public class Inventory {
    private int stock = 1;

    public void buy() {
        if (stock > 0) {
            stock--;
            System.out.println("Item purchased!");
        } else {
            System.out.println("Out of stock!");
        }
    }
}
</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #569CD6">public</span><span style="color: #D4D4D4"> </span><span style="color: #569CD6">class</span><span style="color: #D4D4D4"> </span><span style="color: #4EC9B0">Inventory</span><span style="color: #D4D4D4"> {</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #569CD6">private</span><span style="color: #D4D4D4"> </span><span style="color: #4EC9B0">int</span><span style="color: #D4D4D4"> </span><span style="color: #9CDCFE">stock</span><span style="color: #D4D4D4"> = </span><span style="color: #B5CEA8">1</span><span style="color: #D4D4D4">;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #569CD6">public</span><span style="color: #D4D4D4"> </span><span style="color: #4EC9B0">void</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">buy</span><span style="color: #D4D4D4">() {</span></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #C586C0">if</span><span style="color: #D4D4D4"> (stock &gt; </span><span style="color: #B5CEA8">0</span><span style="color: #D4D4D4">) {</span></span>
<span class="line"><span style="color: #D4D4D4">            stock--;</span></span>
<span class="line"><span style="color: #D4D4D4">            </span><span style="color: #9CDCFE">System</span><span style="color: #D4D4D4">.</span><span style="color: #9CDCFE">out</span><span style="color: #D4D4D4">.</span><span style="color: #DCDCAA">println</span><span style="color: #D4D4D4">(</span><span style="color: #CE9178">&quot;Item purchased!&quot;</span><span style="color: #D4D4D4">);</span></span>
<span class="line"><span style="color: #D4D4D4">        } </span><span style="color: #C586C0">else</span><span style="color: #D4D4D4"> {</span></span>
<span class="line"><span style="color: #D4D4D4">            </span><span style="color: #9CDCFE">System</span><span style="color: #D4D4D4">.</span><span style="color: #9CDCFE">out</span><span style="color: #D4D4D4">.</span><span style="color: #DCDCAA">println</span><span style="color: #D4D4D4">(</span><span style="color: #CE9178">&quot;Out of stock!&quot;</span><span style="color: #D4D4D4">);</span></span>
<span class="line"><span style="color: #D4D4D4">        }</span></span>
<span class="line"><span style="color: #D4D4D4">    }</span></span>
<span class="line"><span style="color: #D4D4D4">}</span></span>
<span class="line"></span></code></pre></div>



<p>If two purchase requests are processed at the same time, both might read <code>stock &gt; 0</code> as true before either decrements it.<br>Both sales go through, but only one item existed!</p>



<h3 class="wp-block-heading">3. Game Server: Item Duplication</h3>



<p>In multiplayer games, if two players pick up the same loot item simultaneously, both could end up owning it — unless access to shared game state is synchronized.<br>This is a classic <strong>race condition</strong> in distributed systems.</p>



<h2 class="wp-block-heading">How to Prevent Race Conditions</h2>



<p>There are several approaches to fix race conditions in Java, depending on the problem and performance needs.</p>



<h3 class="wp-block-heading">1. Use the <code>synchronized</code> Keyword</h3>



<p>You can make a method or block synchronized so only one thread can execute it at a time:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2b2b2b;color:#c7c7c7">Java</span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>public synchronized void withdraw(int amount) {
    if (balance >= amount) {
        balance -= amount;
    }
}
</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #569CD6">public</span><span style="color: #D4D4D4"> </span><span style="color: #569CD6">synchronized</span><span style="color: #D4D4D4"> </span><span style="color: #4EC9B0">void</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">withdraw</span><span style="color: #D4D4D4">(</span><span style="color: #4EC9B0">int</span><span style="color: #D4D4D4"> amount) {</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #C586C0">if</span><span style="color: #D4D4D4"> (balance &gt;= amount) {</span></span>
<span class="line"><span style="color: #D4D4D4">        balance -= amount;</span></span>
<span class="line"><span style="color: #D4D4D4">    }</span></span>
<span class="line"><span style="color: #D4D4D4">}</span></span>
<span class="line"></span></code></pre></div>



<p>or:</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2b2b2b;color:#c7c7c7">Java</span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>public void withdraw(int amount) {
    synchronized(this) {
        if (balance >= amount) {
            balance -= amount;
        }
    }
}
</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #569CD6">public</span><span style="color: #D4D4D4"> </span><span style="color: #4EC9B0">void</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">withdraw</span><span style="color: #D4D4D4">(</span><span style="color: #4EC9B0">int</span><span style="color: #D4D4D4"> amount) {</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #569CD6">synchronized</span><span style="color: #D4D4D4">(</span><span style="color: #569CD6">this</span><span style="color: #D4D4D4">) {</span></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #C586C0">if</span><span style="color: #D4D4D4"> (balance &gt;= amount) {</span></span>
<span class="line"><span style="color: #D4D4D4">            balance -= amount;</span></span>
<span class="line"><span style="color: #D4D4D4">        }</span></span>
<span class="line"><span style="color: #D4D4D4">    }</span></span>
<span class="line"><span style="color: #D4D4D4">}</span></span>
<span class="line"></span></code></pre></div>



<p>Now, only one thread can enter the critical section — preventing concurrent modification.</p>



<h3 class="wp-block-heading">2. Use Locks (<code>ReentrantLock</code>)</h3>



<p><code>ReentrantLock</code> provides more control and flexibility than <code>synchronized</code>.</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2b2b2b;color:#c7c7c7">Java</span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>import java.util.concurrent.locks.ReentrantLock;

public class SafeCounter {
    private int count = 0;
    private final ReentrantLock lock = new ReentrantLock();

    public void increment() {
        lock.lock();
        try {
            count++;
        } finally {
            lock.unlock();
        }
    }
}
</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #569CD6">import</span><span style="color: #D4D4D4"> java.util.concurrent.locks.ReentrantLock;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #569CD6">public</span><span style="color: #D4D4D4"> </span><span style="color: #569CD6">class</span><span style="color: #D4D4D4"> </span><span style="color: #4EC9B0">SafeCounter</span><span style="color: #D4D4D4"> {</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #569CD6">private</span><span style="color: #D4D4D4"> </span><span style="color: #4EC9B0">int</span><span style="color: #D4D4D4"> </span><span style="color: #9CDCFE">count</span><span style="color: #D4D4D4"> = </span><span style="color: #B5CEA8">0</span><span style="color: #D4D4D4">;</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #569CD6">private</span><span style="color: #D4D4D4"> </span><span style="color: #569CD6">final</span><span style="color: #D4D4D4"> </span><span style="color: #4EC9B0">ReentrantLock</span><span style="color: #D4D4D4"> </span><span style="color: #9CDCFE">lock</span><span style="color: #D4D4D4"> = </span><span style="color: #C586C0">new</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">ReentrantLock</span><span style="color: #D4D4D4">();</span></span>
<span class="line"></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #569CD6">public</span><span style="color: #D4D4D4"> </span><span style="color: #4EC9B0">void</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">increment</span><span style="color: #D4D4D4">() {</span></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #9CDCFE">lock</span><span style="color: #D4D4D4">.</span><span style="color: #DCDCAA">lock</span><span style="color: #D4D4D4">();</span></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #C586C0">try</span><span style="color: #D4D4D4"> {</span></span>
<span class="line"><span style="color: #D4D4D4">            count++;</span></span>
<span class="line"><span style="color: #D4D4D4">        } </span><span style="color: #C586C0">finally</span><span style="color: #D4D4D4"> {</span></span>
<span class="line"><span style="color: #D4D4D4">            </span><span style="color: #9CDCFE">lock</span><span style="color: #D4D4D4">.</span><span style="color: #DCDCAA">unlock</span><span style="color: #D4D4D4">();</span></span>
<span class="line"><span style="color: #D4D4D4">        }</span></span>
<span class="line"><span style="color: #D4D4D4">    }</span></span>
<span class="line"><span style="color: #D4D4D4">}</span></span>
<span class="line"></span></code></pre></div>



<p>This approach is useful for complex logic or when you need to try locking with timeouts.</p>



<h3 class="wp-block-heading">3. Use Atomic Variables</h3>



<p>For simple operations, <code>AtomicInteger</code> or other atomic classes provide <strong>thread-safe atomic updates</strong>.</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:flex;align-items:center;padding:10px 0px 10px 16px;margin-bottom:-2px;width:100%;text-align:left;background-color:#2b2b2b;color:#c7c7c7">Java</span><span role="button" tabindex="0" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>import java.util.concurrent.atomic.AtomicInteger;

public class AtomicCounter {
    private final AtomicInteger counter = new AtomicInteger(0);

    public void increment() {
        counter.incrementAndGet();
    }

    public int getValue() {
        return counter.get();
    }
}
</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #569CD6">import</span><span style="color: #D4D4D4"> java.util.concurrent.atomic.AtomicInteger;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #569CD6">public</span><span style="color: #D4D4D4"> </span><span style="color: #569CD6">class</span><span style="color: #D4D4D4"> </span><span style="color: #4EC9B0">AtomicCounter</span><span style="color: #D4D4D4"> {</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #569CD6">private</span><span style="color: #D4D4D4"> </span><span style="color: #569CD6">final</span><span style="color: #D4D4D4"> </span><span style="color: #4EC9B0">AtomicInteger</span><span style="color: #D4D4D4"> </span><span style="color: #9CDCFE">counter</span><span style="color: #D4D4D4"> = </span><span style="color: #C586C0">new</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">AtomicInteger</span><span style="color: #D4D4D4">(</span><span style="color: #B5CEA8">0</span><span style="color: #D4D4D4">);</span></span>
<span class="line"></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #569CD6">public</span><span style="color: #D4D4D4"> </span><span style="color: #4EC9B0">void</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">increment</span><span style="color: #D4D4D4">() {</span></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #9CDCFE">counter</span><span style="color: #D4D4D4">.</span><span style="color: #DCDCAA">incrementAndGet</span><span style="color: #D4D4D4">();</span></span>
<span class="line"><span style="color: #D4D4D4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #569CD6">public</span><span style="color: #D4D4D4"> </span><span style="color: #4EC9B0">int</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">getValue</span><span style="color: #D4D4D4">() {</span></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #C586C0">return</span><span style="color: #D4D4D4"> </span><span style="color: #9CDCFE">counter</span><span style="color: #D4D4D4">.</span><span style="color: #DCDCAA">get</span><span style="color: #D4D4D4">();</span></span>
<span class="line"><span style="color: #D4D4D4">    }</span></span>
<span class="line"><span style="color: #D4D4D4">}</span></span>
<span class="line"></span></code></pre></div>



<p>Atomic variables handle synchronization internally, giving better performance for lightweight operations.</p>



<h3 class="wp-block-heading">4. Design for Immutability</h3>



<p>Instead of fixing race conditions with locks, you can <strong>avoid them</strong> by designing your data as <strong>immutable</strong> — meaning once created, it never changes.<br>This approach is common in functional programming and distributed systems.</p>



<h2 class="wp-block-heading">Race Conditions in Multi-Service Architectures</h2>



<p>Race conditions don’t only happen in threads — they also appear in <strong>microservices</strong> and <strong>databases</strong>.</p>



<p>For instance:</p>



<ul class="wp-block-list">
<li>Two API servers processing the same request simultaneously might write conflicting updates to a shared database.</li>



<li>A cache invalidation race can occur when one service updates a record while another reads stale data.</li>
</ul>



<p><strong>Solutions</strong>:</p>



<ul class="wp-block-list">
<li>Use <strong>transactions</strong> in databases (e.g., optimistic locking in <a href="https://spring.io/projects/spring-data-jpa">JPA</a> or <a href="https://hibernate.org/">Hibernate</a>).</li>



<li>Apply <strong>distributed locks</strong> (e.g., <a href="https://redis.io/docs/latest/develop/clients/patterns/distributed-locks/">Redis Redlock</a>, <a href="https://zookeeper.apache.org/">Zookeeper</a>, or <a href="https://etcd.io/">etcd</a>).</li>



<li>Use <strong>message queues</strong> to serialize operations that must occur in order.</li>
</ul>



<h2 class="wp-block-heading">Testing and Detecting Race Conditions</h2>



<p>Race conditions are notoriously hard to detect because they depend on timing.<br>Some strategies include:</p>



<ul class="wp-block-list">
<li>Running <strong>stress tests</strong> or <strong>load tests</strong> with high concurrency.</li>



<li>Using <strong>Thread Sanitizers</strong> (like IntelliJ’s concurrency analysis tools).</li>



<li>Adding <strong>logging and tracing</strong> to detect inconsistent state.</li>
</ul>



<h2 class="wp-block-heading">Conclusion</h2>



<p>Race conditions are subtle yet powerful sources of bugs in concurrent applications.<br>They can lead to corrupted data, double transactions, or security issues. By learning how to detect and fix a <strong>race condition in Java</strong>, developers can build safer and more predictable applications.</p>



<p></p>
<p>The post <a href="https://www.programmertoolbox.com/race-condition-in-java-explained-with-real-world-examples/">Race Condition in Java Explained &#8211; With Real-World Examples</a> appeared first on <a href="https://www.programmertoolbox.com">Programmer Toolbox</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.programmertoolbox.com/race-condition-in-java-explained-with-real-world-examples/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
