<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Maheshsutar on Medium]]></title>
        <description><![CDATA[Stories by Maheshsutar on Medium]]></description>
        <link>https://medium.com/@maheshsutar1328?source=rss-311fa431219c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*GRa7fsRABKS_YUcF</url>
            <title>Stories by Maheshsutar on Medium</title>
            <link>https://medium.com/@maheshsutar1328?source=rss-311fa431219c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 06:15:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@maheshsutar1328/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Multi-Threading in Java Part 4]]></title>
            <link>https://medium.com/@maheshsutar1328/multi-threading-in-java-part-4-f647c5c2536b?source=rss-311fa431219c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f647c5c2536b</guid>
            <category><![CDATA[volatile-in-java]]></category>
            <category><![CDATA[multithreading-in-java]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[race-condition]]></category>
            <category><![CDATA[threading-in-java]]></category>
            <dc:creator><![CDATA[Maheshsutar]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 10:04:05 GMT</pubDate>
            <atom:updated>2026-06-12T10:04:05.574Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Hidden Bugs of Multithreading: Race Conditions, Atomicity, Visibility &amp; Ordering</h3><p><em>Part 4 of the multithreading series. We’ve learned to create threads, control them, and trace their lifecycle. Now comes the hard truth: the moment multiple threads touch shared data, your code can break in ways that are maddening to reproduce. Here’s exactly how — and a first look at the fixes.</em></p><p>Everything in this series so far has been setup. Threads, lifecycles, methods — all of it leads here, to the part where multithreading actually gets <em>dangerous</em>.</p><p>When you spin up multiple threads (T1, T2, T3 … Tn) running in parallel or concurrently, problems are inevitable. Worse, they’re often invisible in testing and only surface in production — once in a thousand runs, impossible to reproduce on demand. As a developer, your job is to understand them well enough that they never creep in.</p><p>We’ll cover five interlocking problems: <strong>race conditions, atomicity, visibility, ordering,</strong> and the umbrella concept of <strong>thread interference</strong> — plus the keywords (synchronized, volatile) and classes (AtomicInteger) that fix them.</p><p>Let’s start with the most famous one.</p><h3>Race Condition</h3><blockquote><strong><em>Race condition:</em></strong><em> A situation where your program’s </em>final state depends on the order in which threads execute<em> — which thread ran first, how much context switching happened, and so on.</em></blockquote><p>We already know thread order is <strong>non-deterministic.</strong> If T1 and T2 are both ready in RUNNABLE, either might run first. That unpredictability is the soil race conditions grow in.</p><h3>The classic example: count++</h3><pre>int count = 0;<br>// somewhere:<br>count++;</pre><p>This looks like one harmless statement. It is not.</p><blockquote><strong><em>count++ is NOT atomic.</em></strong><em> The CPU doesn&#39;t treat it as a single operation. Internally it&#39;s </em><strong><em>three</em></strong><em> steps:</em></blockquote><ol><li><strong>Read</strong> count from memory</li><li><strong>Increment</strong> count by one</li><li><strong>Write</strong> the updated value back to memory</li></ol><p>“Atomic” means it can’t be divided further. But count++ <em>can</em> be split into those three operations — so it&#39;s non-atomic.</p><p>Wrap it in a class:</p><pre>class Counter {<br>    public int count = 0;<br>    void increment() {<br>        count++;   // the critical section<br>    }<br>}</pre><pre>Counter c1 = new Counter();<br>c1.increment();</pre><p>In a single-threaded program, no problem. In a multithreaded one, multiple threads call c1.increment() — and the result depends on how their three sub-operations interleave.</p><h3>How it actually breaks</h3><p>Two threads, T1 and T2, both reach increment(). With context switching between sub-operations:</p><p>Step T1 T2 1 Reads count = 0 (not running) 2 (switched out) Reads count = 0 3 Increments → 1 (switched out) 4 (switched out) Increments → 1 5 Writes 1 to memory (switched out) 6 (done) Writes 1 — overrides T1!</p><blockquote><strong><em>The bug:</em></strong><em> Logically, two increments should take count from 0 → 2. But the final value is </em><strong><em>1</em></strong><em>. T2’s write clobbered T1’s. One increment vanished.</em></blockquote><p>This happens even in <em>true parallelism</em>: if T1 and T2 run on separate cores at the same instant, both read 0, both increment to 1, both write 1. Same lost update. The root cause is that read-modify-write sequence.</p><h3>Watching it happen</h3><p>A single increment rarely shows the race. Crank it up with a loop:</p><pre>Thread t1 = new Thread(() -&gt; {<br>    for (int i = 1; i &lt;= 10000; i++) c1.increment();<br>});<br>Thread t2 = new Thread(() -&gt; {<br>    for (int i = 1; i &lt;= 10000; i++) c1.increment();<br>});</pre><pre>t1.start();<br>t2.start();<br>t1.join();<br>t2.join();</pre><pre>System.out.println(c1.count);   // expected 20000, but...</pre><p>You expect <strong>20,000</strong>. You get less — and a <em>different</em> number every run: 12109, then 19669, then 11864. Every race condition that occurs drops the count by one. (join() is there so main waits for both threads before printing.)</p><h3>Critical Section &amp; Shared Resource</h3><p>Two terms worth pinning down:</p><ul><li><strong>Critical section</strong> — the risky block of code that multiple threads share. In our code, that’s the increment() method, because every thread calls it on the same c1 object and they can all pile in together.</li><li><strong>Shared resource</strong> — the actual resource being shared. Here it’s count. It could be anything: a List, a bank Account object, etc.</li></ul><blockquote><em>As a developer, it’s your job to write code so race conditions don’t arise — because they introduce subtle, critical bugs.</em></blockquote><h3>The Problem of Atomicity</h3><p>The race condition in count++ traces back to atomicity.</p><blockquote><strong><em>Atomicity:</em></strong><em> Any operation in Java is either </em><strong><em>atomic</em></strong><em> or </em><strong><em>non-atomic</em></strong><em>.</em></blockquote><ul><li><strong>Atomic</strong> = a single, indivisible operation. It either happens <em>completely or not at all</em> — success or failure, no halfway.</li><li><strong>Non-atomic</strong> = an operation that splits into multiple steps. It can be left halfway.</li></ul><p>count++ is non-atomic — read, increment, write. So T1 can read, get switched out, and T2 reads the same old value. That mid-operation switch is the whole problem.</p><p>By contrast, int x = 0; is atomic — a single write you can&#39;t do &quot;half&quot; of. No matter how many threads run it, each does it in one shot; switching happens before or after, never during.</p><h3>Why this terrifies banks</h3><blockquote><strong><em>Bank transfer example:</em></strong><em> Account A sends ₹500 to Account B — deduct ₹500 from A, add ₹500 to B. If this whole operation isn’t atomic, a thread could deduct ₹500 from A, then get context-switched out — and B never receives it. If that thread then ends up stuck in BLOCKED or WAITING indefinitely, the money simply vanishes. A loses ₹500, B gains nothing. A banking app like that is worthless.</em></blockquote><h3>Atomic vs non-atomic, at a glance</h3><p>Always Atomic Non-Atomic Simple assignment: int x = 2; Increment/decrement: x++, x-- Reference assignment: Student s = new Student(); Compound: x = x + 5; Single read / single write / single increment <strong>Check-then-act</strong></p><h3>Check-then-act: the sneaky one</h3><blockquote><em>Whenever you </em><strong><em>check</em></strong><em> something and then </em><strong><em>act</em></strong><em> on it, the whole thing is non-atomic by default.</em></blockquote><pre>if (balance &gt;= amount) {        // CHECK<br>    balance = balance - amount;  // ACT<br>}</pre><p>Here’s how it bites. Initial balance = ₹1000. T1 wants to withdraw ₹500, T2 wants ₹600.</p><ol><li>T1 checks: 1000 ≥ 500? Yes. T1 enters the block.</li><li>T1 is about to subtract → <strong>switched out.</strong></li><li>T2 checks: 1000 ≥ 600? Yes. T2 enters the block.</li><li>T2 subtracts: 1000 − 600 = ₹400.</li><li>T2 switched out. T1 resumes — <em>directly at the subtraction</em>, since it already passed the check.</li><li>T1 subtracts: 400 − 500 = <strong>−100.</strong></li></ol><blockquote><em>Both transactions “succeeded,” giving away ₹1100 from an account that held ₹1000. T1’s check was stale — it passed earlier, but the balance changed underneath it. You should never be able to send ₹1100 from a ₹1000 account.</em></blockquote><h3>A bonus edge case: doubles</h3><blockquote><em>In some compilers, even </em><em>double d = 112.234; is non-atomic. A </em><em>double is </em><strong><em>64 bits</em></strong><em>, and the JVM sometimes writes it in </em><strong><em>two 32-bit halves</em></strong><em>. If a thread writes the first half and gets switched before the second, another thread can corrupt the value. So a double store isn&#39;t always atomic.</em></blockquote><h3>Fixing atomicity (preview)</h3><blockquote><em>Two main solutions:</em></blockquote><ol><li><strong>synchronized</strong> block</li><li><strong>Atomic classes</strong> like AtomicInteger (and AtomicDouble), which use a <strong>CAS (Compare-And-Swap)</strong> mechanism internally.</li></ol><blockquote><em>Solve atomicity, and you solve the race condition too.</em></blockquote><h3>The Problem of Visibility</h3><blockquote><strong><em>Visibility:</em></strong><em> One thread updates a variable, but another thread </em>never sees the update<em> — it becomes “invisible” to it. T1 sets </em><em>count = 1, but T2 still reads the old </em><em>0.</em></blockquote><h3>Why it happens</h3><pre>Core 1 + Registers          Core 2 + Registers<br>       │                            │<br>   L1/L2 Cache (Core 1)      L1/L2 Cache (Core 2)<br>       └──────────┬─────────────────┘<br>                  ▼<br>        RAM (shared main memory)</pre><p>RAM is slow, so each core caches values in its own faster cache (and registers). That local caching is what breaks visibility:</p><pre>Initially: flag = false in RAM<br>   ↓<br>T1 reads flag=false into ITS cache. T2 reads flag=false into ITS cache.<br>   ↓<br>T1 changes flag → true, writes it back to RAM (RAM now has true)<br>   ↓<br>BUT T2 keeps reading from ITS OWN cache, still false<br>   ↓<br>T1&#39;s new value is INVISIBLE to T2 → it reads stale &quot;false&quot; forever</pre><blockquote><em>With a single thread this never happens — it always reads a consistent value. The problem only appears with two or more threads, because T2’s cache holds a stale copy.</em></blockquote><h3>The loop that won’t die</h3><pre>static boolean flag = false;</pre><pre>Thread t1 = new Thread(() -&gt; {<br>    try { Thread.sleep(1000); } catch (Exception e) {}<br>    flag = true;   // change after 1 second<br>});</pre><pre>Thread t2 = new Thread(() -&gt; {<br>    while (!flag) {<br>        // do nothing — loop while flag is false<br>    }<br>    System.out.println(&quot;Thread 2 finished&quot;);<br>});</pre><pre>t1.start();<br>t2.start();</pre><p>This <strong>never stops.</strong> Even after T1 sets flag = true in RAM, T2 keeps reading flag from its own cache (still false), so the loop runs forever.</p><blockquote><strong><em>Curious side note:</em></strong><em> Put a </em><em>System.out.println(...) inside the loop and the code </em>does<em> stop — because </em><em>println() is internally </em><strong><em>synchronized</em></strong><em>, and synchronization forces a read straight from RAM. Remove the print, and the infinite loop returns.</em></blockquote><h3>The fix: volatile</h3><pre>static volatile boolean flag = false;</pre><blockquote><strong><em>volatile</em></strong><em> says: whenever any thread reads or writes this variable, go </em>directly to RAM<em> — never the cache. So when T1 writes true to RAM and T2 compares against RAM, T2 sees the change and exits. &quot;Thread 2 finished&quot; prints.</em></blockquote><p>But here’s the trap people fall into:</p><blockquote><strong><em>volatile does NOT solve race conditions.</em></strong><em> Write </em><em>volatile int count = 0; then </em><em>count++, and the race condition still happens. </em><em>volatile only guarantees reads/writes hit RAM. The race condition came from a three-step non-atomic operation — a completely different problem.</em></blockquote><p>synchronized can also fix visibility (it flushes caches and forces RAM reads when locks are acquired/released), but we generally prefer volatile for pure visibility, reserving synchronized for race conditions.</p><h3>The Problem of Ordering</h3><blockquote><strong><em>Ordering:</em></strong><em> The sequence in which instructions execute may not match the order you wrote them — thanks to JVM/compiler and CPU optimizations.</em></blockquote><pre>int a = 1;<br>int b = 2;</pre><p>You assume a is set first, then b. But the JVM optimizes aggressively, and it&#39;s <em>not guaranteed</em> — it might set b first.</p><p>The causes: <strong>compiler optimization</strong> (reordering for efficiency) and <strong>CPU reordering</strong> (running instructions in a more efficient order), among others.</p><blockquote><strong><em>Java’s guarantee:</em></strong><em> Any reordering it does will </em>not<em> break a </em><strong><em>single-threaded</em></strong><em> program. It only reorders where the meaning doesn’t change. So </em><em>int a = 1; int b = 2; can be safely reordered — but </em><em>int b = a + 1; cannot, because </em><em>b depends on </em><em>a. Java promises correctness for single-threaded code, </em>not<em> for multithreaded code (which is non-deterministic and unpredictable).</em></blockquote><h3>Where it bites</h3><pre>int x = 0;<br>boolean flag = false;</pre><pre>// Thread 1:<br>x = 10;<br>flag = true;</pre><pre>// Thread 2:<br>if (flag == true) {<br>    System.out.println(x);<br>}</pre><p>You expect: T1 sets x = 10 and flag = true, then T2 sees the flag and prints <strong>10</strong>.</p><p>But the output might be <strong>0.</strong> Why? T1 might <em>reorder</em> its two lines — setting flag = true first, then x = 10. If T1 sets the flag and gets switched out before setting x, T2 runs, sees flag == true, and prints x — still <strong>0.</strong></p><blockquote><strong><em>Why it’s so dangerous:</em></strong><em> This bug needs reordering </em>and<em> unlucky context switching to align. So in production it might show up 1 in 10 times, or rarer — but it </em>will<em> show up eventually. Reproducing it for debugging is brutal, because it rides on probability. This is exactly why multithreaded code has to handle so many edge cases.</em></blockquote><h3>Fixes for ordering</h3><ul><li><strong>synchronized</strong> prevents reordering (via locks).</li><li><strong>volatile</strong> variables aren&#39;t reordered.</li></ul><blockquote><em>Net effect: </em><strong><em>volatile</em></strong><em> guarantees ordering </em>and<em> visibility, but not atomicity. </em><strong><em>synchronized</em></strong><em> guarantees all three.</em></blockquote><h3>Thread Interference (and the Real Enemy)</h3><blockquote><strong><em>Thread interference:</em></strong><em> Everything above </em>is<em> thread interference — multiple threads disturbing each other’s work. When threads share a resource, T1 changes something and T2 hits a visibility problem, a race condition, or an ordering issue.</em></blockquote><p>The causes: non-atomic operations, shared resources, race conditions, ordering, visibility. And the outcome is the thing you should actually fear:</p><blockquote><strong><em>Data inconsistency</em></strong><em> — the most dangerous result of all. You build your entire application </em>around your data<em>. In a banking app, the data is account balances and user information. </em>Every<em> application is built around data. If your data becomes inconsistent, countless problems follow.</em></blockquote><p>The whole chain:</p><pre>Non-atomic ops + Shared resources + Reordering + Caching<br>   ↓ lead to<br>Race Conditions, Visibility issues, Ordering issues<br>   ↓ collectively<br>THREAD INTERFERENCE<br>   ↓ which causes<br>DATA INCONSISTENCY  ← the real danger</pre><h3>The Solutions, Summarized</h3><p>Solution Solves Notes <strong>synchronized block</strong> Race condition, Atomicity, Visibility, Ordering Uses locking; covered next <strong>volatile keyword</strong> Visibility, Ordering Forces RAM reads/writes; does NOT fix races/atomicity <strong>Atomic classes</strong> (AtomicInteger, …) Atomicity, Race condition Uses CAS internally <strong>Other locking mechanisms</strong> All Proper locks; covered later</p><p>Quick mapping:</p><ul><li><strong>Race condition / Atomicity</strong> → synchronized or AtomicInteger</li><li><strong>Visibility / Ordering</strong> → volatile (or synchronized)</li></ul><h3>Wrapping Up</h3><p>The dark side of multithreading, mapped out:</p><ul><li><strong>Race condition</strong> — output depends on thread execution order (the count++ demo never reaching 20,000).</li><li><strong>Atomicity</strong> — operations that split into multiple steps, the check-then-act trap, the banking horror story, the double edge case.</li><li><strong>Visibility</strong> — threads reading stale values from their own cache instead of RAM (fixed by volatile).</li><li><strong>Ordering</strong> — the JVM/CPU reordering instructions and breaking multithreaded assumptions.</li><li><strong>Thread interference</strong> — the umbrella cause that ultimately leads to data inconsistency.</li></ul><p>These are the edge cases that separate code that “works on my machine” from code that’s actually correct under concurrency. Handling all of them is the real job.</p><p>Next in the series: how we <em>protect</em> against these problems for real — synchronized in depth, AtomicInteger, locking mechanisms, and writing multithreaded code you can actually trust.</p><p><em>If this gave you a healthy fear of shared mutable state, give it a clap and follow along — the next part is all about the fixes.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f647c5c2536b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-Threading in Java Part 3]]></title>
            <link>https://medium.com/@maheshsutar1328/multi-threading-in-java-part-3-7b0049ea3137?source=rss-311fa431219c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b0049ea3137</guid>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[process]]></category>
            <category><![CDATA[threading-in-java]]></category>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[multithreading-in-java]]></category>
            <dc:creator><![CDATA[Maheshsutar]]></dc:creator>
            <pubDate>Sun, 07 Jun 2026 04:01:01 GMT</pubDate>
            <atom:updated>2026-06-07T04:01:01.533Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java Thread Methods, Demystified: sleep, join, yield, interrupt, and Daemon Threads</h3><p><em>Part 3 of the multithreading series. We’ve covered the foundations and the thread lifecycle. Now we get to the toolbox — the methods that actually let you control threads — and finish with daemon threads, the quiet background workers behind things like garbage collection.</em></p><p>So far this series has been about understanding: what processes and threads are, how to create them, and the states they move through. This part is more practical. These are the methods you’ll reach for constantly when writing real multithreaded code — and a few you should know exist but almost never touch.</p><p>We’ll walk through sleep(), join(), yield(), interrupt(), the confusing pair isInterrupted() vs interrupted(), isAlive(), naming, priority, and finally daemon threads. I&#39;ll flag which ones matter in production and which are basically trivia.</p><p>Let’s start with the one you’ve probably already used.</p><h3>sleep()</h3><blockquote><strong><em>What it does:</em></strong><em> </em><em>Thread.sleep() puts a thread into the </em><strong><em>TIMED WAITING</em></strong><em> state for a given duration. During that time, the thread isn&#39;t running.</em></blockquote><p>The time is in milliseconds. When it’s up, the thread returns to RUNNABLE, and once it gets CPU time again, it resumes.</p><pre>System.out.println(&quot;Main thread starts&quot;);<br>try {<br>    Thread.sleep(2000);   // current thread sleeps 2 seconds<br>} catch (InterruptedException e) {<br>}<br>System.out.println(&quot;Main thread ends&quot;);</pre><p>Output: “Main thread starts” → a 2-second pause → “Main thread ends”. Internally, the thread goes RUNNING → TIMED WAITING → (after time) RUNNABLE → RUNNING.</p><blockquote><strong><em>Heads up:</em></strong><em> </em><em>Thread.sleep() throws a </em>checked<em> </em><em>InterruptedException. You must handle it in a try-catch (or declare it with </em><em>throws), or you&#39;ll get a compilation error.</em></blockquote><p>And one rule that bites people later:</p><blockquote><strong><em>sleep() does NOT release locks.</em></strong><em> If a sleeping thread had entered a critical section and grabbed a lock, it keeps that lock for the entire sleep. Every other thread waiting on that lock just… waits. </em><strong><em>TIMED WAITING never releases locks.</em></strong><em> (This matters a lot once you study locks.)</em></blockquote><h3>join()</h3><blockquote><strong><em>What it does:</em></strong><em> When you call </em><em>t1.join() from inside another thread (say, the main thread), that calling thread goes into the </em><strong><em>WAITING</em></strong><em> state until </em><em>t1 finishes. In plain English: &quot;Let t1 finish before you continue.&quot;</em></blockquote><p>Without join(), order is non-deterministic:</p><pre>System.out.println(&quot;Main thread starts&quot;);<br>Thread t1 = new Thread(() -&gt; System.out.println(&quot;Thread-0 starts&quot;));<br>t1.start();<br>System.out.println(&quot;Main thread ends&quot;);</pre><p>Most likely you’ll see “Main thread starts” → “Main thread ends” → “Thread-0 starts”, because after start(), T1 may not get CPU time immediately, so main races ahead. But that&#39;s not guaranteed.</p><p>Add join() and you take control:</p><pre>Thread t1 = new Thread(() -&gt; {<br>    try { Thread.sleep(2000); } catch (Exception e) {}<br>    System.out.println(&quot;Thread-0 starts&quot;);<br>});<br>t1.start();<br>t1.join();   // main waits until t1 finishes<br>System.out.println(&quot;Main thread ends&quot;);</pre><p>Now it’s deterministic: “Main thread starts” → 2-second pause → “Thread-0 starts” → “Main thread ends”. The main thread sits in WAITING until t1 is completely done.</p><pre>Main reaches t1.join()<br>   ↓<br>Main goes into WAITING<br>   ↓<br>t1 runs (RUNNABLE → ... → TERMINATED)<br>   ↓<br>The moment t1 terminates, main returns to RUNNABLE<br>   ↓<br>Main runs its remaining lines, then terminates</pre><p>There’s an overloaded version too: t1.join(2000) says &quot;wait only 2 seconds for t1. If it finishes in time, great; otherwise, resume your own work.&quot;</p><blockquote><strong><em>Key difference:</em></strong><em> Plain </em><em>join() puts the calling thread into </em><strong><em>WAITING</em></strong><em>, but </em><em>join(time) puts it into </em><strong><em>TIMED WAITING</em></strong><em> — just like </em><em>sleep() — because you&#39;re only waiting for a fixed amount of time.</em></blockquote><h3>yield()</h3><blockquote><strong><em>What it does:</em></strong><em> A static method. The current thread becomes generous — it says, “If I’m running and another thread of equal priority is ready to run, I’m willing to give up my CPU time for it.”</em></blockquote><p>Three things you need to internalize about yield():</p><ol><li>It’s only a <strong>request/suggestion to the OS</strong> — which can reject it outright. We can’t dictate CPU scheduling through Java methods; the OS and CPU decide that.</li><li>The thread you call it on does <em>not</em> go to WAITING, TIMED WAITING, or BLOCKED.</li><li>It goes <strong>only to RUNNABLE.</strong></li></ol><pre>Thread t1 = new Thread(() -&gt; {<br>    for (int i = 1; i &lt;= 10; i++) {<br>        System.out.println(&quot;T1 says &quot; + i);<br>        Thread.yield();   // willing to give CPU to T2<br>    }<br>});</pre><pre>Thread t2 = new Thread(() -&gt; {<br>    for (int i = 1; i &lt;= 10; i++) System.out.println(&quot;T2 says &quot; + i);<br>});</pre><pre>t1.start();<br>t2.start();</pre><p>When the OS respects it, T1 prints 1, then yields → T2 runs several numbers → T1 prints 2, yields again, and so on. T2 effectively gets more chances because T1 keeps stepping aside.</p><blockquote><strong><em>Reality check:</em></strong><em> We almost never use </em><em>yield() in production — the OS can ignore it entirely. Its only real use is </em>testing<em> — to understand scheduling or nudge another thread to run more often.</em></blockquote><h3>interrupt()</h3><blockquote><strong><em>What it does:</em></strong><em> Sends a </em>signal<em> to a thread that it should stop whatever it’s doing. Crucially — it’s only a signal. It does </em><strong><em>not</em></strong><em> force the thread to stop.</em></blockquote><p>Every thread carries an <strong>interrupt flag</strong> (a boolean, default false). Calling t1.interrupt() just flips that flag to true. The thread keeps doing its thing; you can&#39;t force it to halt.</p><p>So this does <em>not</em> stop the loop:</p><pre>Thread t1 = new Thread(() -&gt; {<br>    while (true) {<br>        System.out.println(&quot;running&quot;);<br>    }<br>});<br>t1.start();<br>t1.interrupt();   // only sets the flag — loop runs forever</pre><p>The point of interrupt() is to let you <strong>gracefully</strong> stop. Instead of while(true), check the flag:</p><pre>Thread t1 = new Thread(() -&gt; {<br>    while (!Thread.currentThread().isInterrupted()) {<br>        System.out.println(&quot;running&quot;);<br>    }<br>});<br>t1.start();<br>t1.interrupt();   // flag becomes true → condition fails → loop exits</pre><p>Here, “running” might not print even once, because the flag flips to true right after starting. To let it run for a controlled duration:</p><pre>Thread t1 = new Thread(() -&gt; {<br>    while (!Thread.currentThread().isInterrupted()) {<br>        System.out.println(&quot;running&quot;);<br>    }<br>});<br>t1.start();</pre><pre>Thread.sleep(2000);   // let it run 2 seconds<br>t1.interrupt();       // now stop it</pre><p>No longer an infinite loop — it prints for 2 seconds, then stops. <em>That’s</em> graceful handling.</p><p>Where this shines in production:</p><ul><li>Making a thread run <strong>until an external condition</strong> — set from outside via the interrupt flag.</li><li><strong>Cancelling a long-running background task</strong> — it runs until someone calls t1.interrupt().</li><li><strong>Stopping a thread pool</strong> (covered later in the series).</li></ul><h3>isInterrupted() vs interrupted()</h3><p>People constantly confuse these two <em>checking</em> methods. (Note: interrupt() is for interrupting; these two are for <em>reading</em> the flag.)</p><p>Method What it does <strong>isInterrupted()</strong> Returns the flag’s value. Does <strong>NOT</strong> reset it. <strong>interrupted()</strong> Returns the flag’s value, <em>and also resets it to false</em>.</p><blockquote><strong><em>The whole difference:</em></strong><em> </em><em>interrupted() resets the flag after reading; </em><em>isInterrupted() just reports the current value.</em></blockquote><p>And here’s a use case that explains a recurring mystery:</p><blockquote><strong><em>Why is </em></strong><strong><em>InterruptedException checked?</em></strong><em> A thread that&#39;s sleeping, joining, or in WAITING/TIMED WAITING — if you call </em><em>interrupt() on it, you get an </em><em>InterruptedException. When you call </em><em>Thread.sleep(), the compiler can&#39;t know whether you&#39;ll interrupt that thread. If you do, it throws this exception. That&#39;s exactly why you keep having to handle it.</em></blockquote><h3>isAlive()</h3><blockquote><strong><em>What it does:</em></strong><em> Checks whether a thread is alive. A thread is alive from the moment it </em><strong><em>starts</em></strong><em> until it </em><strong><em>terminates</em></strong><em>. Before starting → dead. After terminating → dead.</em></blockquote><pre>Thread t1 = new Thread(() -&gt; {<br>    try { Thread.sleep(2000); } catch (Exception e) {}<br>});</pre><pre>System.out.println(t1.isAlive());   // false (not started)<br>t1.start();<br>System.out.println(t1.isAlive());   // true (alive)</pre><pre>Thread.sleep(3000);                 // main sleeps 3 seconds</pre><pre>System.out.println(t1.isAlive());   // false (t1 terminated after its 2s)</pre><p>Output: false → true → (3-second wait) → false. T1 is alive for its 2 seconds (even while in TIMED WAITING), then dies.</p><h3>currentThread(), getName(), setName()</h3><p>currentThread() hands you a reference to the running thread — and with that reference you can call any other method on it.</p><pre>Thread t1 = new Thread(() -&gt; {<br>    System.out.println(Thread.currentThread().getName());<br>});<br>t1.start();   // prints &quot;Thread-0&quot; (the default name)</pre><p>You can also <em>set</em> a custom name:</p><pre>Thread t1 = new Thread(() -&gt; {<br>    System.out.println(Thread.currentThread().getName());<br>});<br>t1.setName(&quot;Worker-1&quot;);<br>t1.start();   // now prints &quot;Worker-1&quot;</pre><blockquote><strong><em>Why bother?</em></strong><em> For </em><strong><em>logging</em></strong><em> in multithreaded code — to see which thread is doing what. Default names like “Thread-0” are useless. In thread pools, threads are often named “workers” (like “Worker-1”), which you’ll meet later.</em></blockquote><h3>Thread Priority</h3><blockquote><em>Every thread in Java has a priority. It tells the OS that a thread is more (or less) important and should get more (or less) CPU preference.</em></blockquote><p>There are three priority constants in the Thread class:</p><p>Constant Value MIN_PRIORITY 1 NORM_PRIORITY (default) 5 MAX_PRIORITY 10</p><p>So priority ranges from 1 to 10, and every thread defaults to 5.</p><pre>Thread t1 = new Thread(() -&gt; System.out.println(&quot;Custom thread running&quot;));<br>t1.start();<br>System.out.println(t1.getPriority());   // 5 (default)<br>t1.setPriority(10);                      // bump to maximum</pre><p>But — and this is the catch:</p><blockquote><strong><em>Priority is only a hint.</em></strong><em> Java can’t control which thread runs; the OS decides and may completely ignore priority. There’s </em>no guarantee<em> that a high-priority thread runs first. The OS may respect it, partially respect it, or ignore it entirely. This is why we rarely use it — it just exists.</em></blockquote><h3>Daemon Threads (This One’s Important)</h3><blockquote><strong><em>A daemon thread is any thread that runs in the background.</em></strong></blockquote><p>Java splits all threads into two categories:</p><ul><li><strong>User threads</strong> — everything we’ve made so far.</li><li><strong>Daemon threads</strong> — background tasks.</li></ul><p>The difference is everything:</p><ul><li><strong>User thread:</strong> Even if the main thread finishes, the program keeps running until the user thread finishes. The program won’t end while a user thread is still alive.</li><li><strong>Daemon thread:</strong> A background task. The moment the <strong>main thread finishes</strong>, the daemon thread is <strong>stopped immediately</strong> — regardless of whether it completed its work.</li></ul><p>A user thread keeps the program alive:</p><pre>Thread t1 = new Thread(() -&gt; {<br>    while (true) System.out.println(&quot;running&quot;);<br>});<br>t1.start();<br>return;   // main ends, but t1 (user thread) keeps printing forever</pre><p>Make it a daemon with setDaemon(true):</p><pre>Thread t1 = new Thread(() -&gt; {<br>    while (true) System.out.println(&quot;running&quot;);<br>});<br>t1.setDaemon(true);   // mark as daemon BEFORE starting<br>t1.start();<br>// main ends immediately → daemon t1 stops → &quot;running&quot; may never print</pre><blockquote><strong><em>How it works:</em></strong><em> Every thread has a daemon flag (default </em><em>false, meaning user thread by default). </em><em>setDaemon(true) marks it as a background task that dies the instant the main thread finishes.</em></blockquote><h3>The Real-World Payoff: Garbage Collection</h3><p>Here’s where daemon threads click:</p><blockquote><strong><em>Garbage collection runs on a daemon thread.</em></strong><em> Think about it — how long should garbage collection run? Only as long as your main program runs. The moment your program ends, garbage collection should stop too.</em></blockquote><p>Any background task that should live only as long as the main thread is a perfect candidate for a daemon thread. Garbage collection is exactly that — which is why Java’s entire GC is built on a daemon thread.</p><h3>Every Method at a Glance</h3><p>Method Static? Purpose Production use? sleep(ms) Yes TIMED WAITING for a time; does NOT release locks Yes join() No Calling thread WAITs until target finishes Yes join(ms) No Waits only for given time (TIMED WAITING) Yes yield() Yes Suggests giving CPU to equal-priority threads No (testing) interrupt() No Sets interrupt flag = true; doesn&#39;t force stop Yes (graceful stop) isInterrupted() No Returns flag value (no reset) Yes interrupted() Yes Returns flag value AND resets to false Yes isAlive() No Checks if thread is alive Yes currentThread() Yes Returns reference of running thread Yes getName()/setName() No Get/set thread name (logging) Yes getPriority()/setPriority() No Get/set priority (1–10); only a hint Rarely setDaemon(true) No Marks thread as background daemon Yes</p><h3>Wrapping Up</h3><p>That’s the toolbox:</p><ul><li>sleep() for TIMED WAITING (and remember — it holds onto locks).</li><li>join() / join(time) to control execution order.</li><li>yield() — a polite suggestion the OS can ignore (rarely used).</li><li>interrupt() — a signal, handled gracefully with a flag check.</li><li>isInterrupted() vs interrupted() — and why InterruptedException is checked.</li><li>isAlive(), naming for logging, and priority as a mere hint.</li><li><strong>Daemon threads</strong> — background workers that die with the main thread, the way garbage collection does.</li></ul><p>A practical tip to close: actually <em>practice</em> these. Get comfortable with which ones matter (sleep, join, interrupt, setDaemon) and which are mostly trivia (yield, and usually setPriority).</p><p>Next up, the part everyone’s been waiting for: the <strong>problems</strong> that creep into multithreaded code — race conditions, atomicity, visibility, ordering — and how we begin to solve them.</p><p><em>If this made the thread methods finally stick, give it a clap and follow along — the next part digs into the real bugs of multithreading and how to fix them.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b0049ea3137" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-Threading in Java Part 2]]></title>
            <link>https://medium.com/@maheshsutar1328/multi-threading-in-java-part-2-8a9647c3f03f?source=rss-311fa431219c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a9647c3f03f</guid>
            <category><![CDATA[threading-in-java]]></category>
            <category><![CDATA[process]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[multithreading-in-java]]></category>
            <category><![CDATA[threads]]></category>
            <dc:creator><![CDATA[Maheshsutar]]></dc:creator>
            <pubDate>Sun, 31 May 2026 04:01:00 GMT</pubDate>
            <atom:updated>2026-05-31T04:01:00.463Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating Threads in Java: Two Ways, One Lifecycle, and the Bugs Hiding in Between</h3><p><em>Part 2 of the multithreading series. Last time we built the foundation — programs, processes, threads. Now we get our hands dirty: actually creating threads, watching them move through their lifecycle, and meeting the non-determinism that makes multithreaded code so slippery.</em></p><p>In the first part, we answered the slow, foundational questions: what’s a program, what’s a process, what’s a thread. If processes and threads still feel fuzzy, go read that first — this builds directly on it.</p><p>This time it’s hands-on. We’ll create threads two different ways, figure out which one is better (and why), poke at thread names and IDs, untangle the classic start() vs run() confusion, and then map out the <em>entire</em> lifecycle a thread passes through. Along the way, we&#39;ll hit a couple of interview questions that come up constantly.</p><p>Let’s start with the obvious question: how do you even make a thread?</p><h3>Two Ways to Create a Thread</h3><p>In Java, everything is an object, and to make anything you need a class. Threads are no exception. Java gives you two routes:</p><ol><li><strong>Extend the </strong><strong>Thread class</strong> — Java ships a built-in Thread class; you inherit from it.</li><li><strong>Implement the </strong><strong>Runnable interface</strong> — Java ships a Runnable interface; you implement it.</li></ol><h3>Method 1: Extending Thread</h3><p>Create a class that extends Thread. The Thread class has a run() method you must override. Whatever you put inside run() is the work the thread does.</p><pre>class MyThread extends Thread {<br>    @Override<br>    public void run() {<br>        System.out.println(&quot;Thread is running&quot;);<br>    }<br>}</pre><pre>// In main:<br>MyThread t1 = new MyThread();<br>t1.start();</pre><p>Call t1.start(), and &quot;Thread is running&quot; prints. The thread then terminates, the main method terminates, and the program ends.</p><h3>What Actually Happens on start()</h3><p>This part is worth slowing down for:</p><pre>You call t1.start()<br>   ↓<br>JVM asks the OS to create a new thread<br>   ↓<br>OS creates the thread (inside the same process)<br>   ↓<br>Thread gets its own Stack space + Program Counter<br>   ↓<br>Thread is ready to run<br>   ↓<br>Internally, start() calls the thread&#39;s run() method<br>   ↓<br>CPU executes the thread — it starts running</pre><p>Remember: until you made this thread, the process already had a default <strong>main thread</strong> running the flow. Now a second thread (referenced by t1) exists alongside it.</p><h3>Method 2: Implementing Runnable</h3><p>The Runnable interface represents anything that <em>can be run</em>. With it, you don&#39;t create a thread directly — you create a <strong>task</strong>, then hand that task to a Thread.</p><pre>class MyRunnable implements Runnable {<br>    @Override<br>    public void run() {<br>        System.out.println(&quot;Thread is running&quot;);<br>    }<br>}</pre><pre>// In main:<br>MyRunnable r1 = new MyRunnable();<br>Thread t1 = new Thread(r1);   // pass the runnable into Thread&#39;s constructor<br>t1.start();</pre><blockquote><strong><em>Fun fact:</em></strong><em> The </em><em>Thread class itself internally implements </em><em>Runnable (</em><em>class Thread implements Runnable). So when you extend </em><em>Thread, you&#39;re </em>indirectly<em> implementing </em><em>Runnable too.</em></blockquote><p>The behind-the-scenes flow is identical: start() asks the OS for a thread, it gets its stack and PC, then executes run() — this time, the Runnable&#39;s version.</p><h3>Thread vs. Task: A Subtle But Important Difference</h3><p>Here’s the conceptual split:</p><ul><li><strong>Extending Thread</strong> → you are <em>defining a thread</em>. Your MyThread <em>is a</em> Thread (because extends means an &quot;is-a&quot; relationship). You call start() directly on its object.</li><li><strong>Implementing Runnable</strong> → you are <em>defining a task</em>. You describe <em>what work</em> to do inside run(). To run it, you wrap it in a separate Thread object.</li></ul><p>The hierarchy looks like this:</p><pre>Runnable (interface)<br>           /                    \<br>   Thread (class)          MyRunnable (your class)<br>        |                  implements Runnable directly<br>   MyThread (your class)<br>   extends Thread → indirectly implements Runnable</pre><h3>Which Should You Use? Always Prefer Runnable</h3><p>Both work, but Runnable wins for several solid reasons.</p><p><strong>1. Separation of concern.</strong> Implementing Runnable means you&#39;re defining a <em>task</em> (what to do) rather than a <em>thread</em> (how to run it). The thread already exists in Java — you just tell it what work to perform.</p><p><strong>2. Reusability.</strong> If a class implements Runnable, you can hand the same logic to multiple threads:</p><pre>Thread t1 = new Thread(r1);<br>Thread t2 = new Thread(r1);<br>Thread t3 = new Thread(r1);</pre><p>All three now run the same logic.</p><p><strong>3. Multiple inheritance.</strong> This is the big one.</p><blockquote><em>In Java, you can implement </em>multiple interfaces<em>, but extend </em>only one class<em>. If your class extends </em><em>Thread, it&#39;s locked — it can&#39;t extend anything else. If it merely implements </em><em>Runnable, it can still extend another class and implement more interfaces.</em></blockquote><p>A Runnable-implementing class can also behave as a normal class — own instance variables, own methods — while still having a run() method a thread can execute.</p><p><strong>4. Lambdas.</strong> Runnable is a <em>functional interface</em> (single abstract method), so you can skip the whole class and use a lambda:</p><pre>Thread t1 = new Thread(() -&gt; {<br>    System.out.println(&quot;Thread is running&quot;);<br>});<br>t1.start();</pre><blockquote><strong><em>Bottom line:</em></strong><em> Whether you extend </em><em>Thread or implement </em><em>Runnable, behind the scenes you&#39;re telling the OS to create a new thread — give it a stack, a program counter, and run it independently. But </em><em>Runnable keeps your code flexible.</em></blockquote><h3>Thread Names and IDs (and Why IDs Are Basically Useless)</h3><p>In production, multithreaded code gets complicated fast — many threads running at their own unpredictable times. That makes debugging painful, and knowing each thread’s <em>name</em> helps enormously.</p><p>Java’s Thread class has a static method currentThread() that returns a reference to the running thread:</p><pre>System.out.println(Thread.currentThread().getName());  // prints &quot;main&quot;<br>System.out.println(Thread.currentThread().getId());    // prints 1 by default</pre><p>The default main thread is named &quot;main&quot; with ID 1.</p><blockquote><strong><em>Why can’t you call </em></strong><strong><em>Thread.getName() directly?</em></strong><em> Because </em><em>getName() is </em>non-static<em> — you need an object to call it on. So you fetch the current thread object first via </em><em>Thread.currentThread(), then call </em><em>getName() on it.</em></blockquote><p>About that ID method:</p><blockquote><strong><em>getId() is deprecated.</em></strong><em> Java wants you to stop using it. The reasoning: thread IDs give a </em>false sense of meaning<em>. Nobody calls a thread by its ID in real life — IDs like 1, 2, 3 have no meaningful order. Start a few threads and any of them might run first. So the method serves no real purpose.</em></blockquote><p>A critical gotcha when you create your own thread:</p><blockquote><strong><em>If you create a thread but never call </em></strong><strong><em>start(), its logic never runs.</em></strong><em> Without </em><em>start(), you never tell the OS to create the thread, so </em><em>run() (your lambda) is never invoked.</em></blockquote><h3>Order Is Not Guaranteed</h3><p>Create two threads, each printing its name and ID, then start both:</p><pre>t1.start();<br>t2.start();</pre><p>A beginner expects T1’s output fully, then T2’s. Reality:</p><blockquote><strong><em>Java does not preserve order.</em></strong><em> The output comes in unpredictable sequences, and running the same program again gives a </em>different<em> order each time.</em></blockquote><p>The thread <em>name</em>, though, is genuinely useful — for <strong>logging</strong> in production, to see which thread is doing what. You can even rename threads with setName(), since the auto-generated &quot;Thread-0&quot;, &quot;Thread-1&quot; names tell you nothing.</p><h3>start() vs. run(): The Classic Confusion</h3><p>Both the Thread class and the Runnable interface have a run() method — and that&#39;s the one you override with your logic. So why call start() instead of run() directly?</p><p><strong>Calling </strong><strong>t1.start():</strong></p><ul><li>Tells the OS to create a NEW thread</li><li>The new thread gets its own stack + PC</li><li>Internally calls run() on that new thread</li><li>Output: Current thread is Thread-0</li></ul><p><strong>Calling </strong><strong>t1.run() directly:</strong></p><ul><li>NO new thread is created</li><li>It’s just a normal method call on the main thread</li><li>The logic runs on the MAIN thread</li><li>Output: Current thread is main</li></ul><blockquote><strong><em>The key insight:</em></strong><em> Calling </em><em>t1.run() directly runs the logic on the </em>main thread<em>, because no actual thread was created. A thread is only born when you call </em><em>start() — which internally asks the OS for a new thread, which then calls </em><em>run().</em></blockquote><h3>Two Interview Questions You’ll Definitely Get</h3><p><strong>Q1: What happens if you call </strong><strong>run() directly instead of </strong><strong>start()?</strong> The logic runs on the <strong>main thread</strong> — no new thread is created — so Thread.currentThread().getName() returns &quot;main&quot;.</p><p><strong>Q2: Can you start the same thread twice?</strong> <strong>No.</strong> Calling start() twice throws an IllegalThreadStateException. Once a thread has started, run, and finished, its lifecycle is over — you can&#39;t restart it.</p><pre>t1.start();<br>t1.start();   // throws IllegalThreadStateException</pre><p>This makes more sense once we look at the lifecycle.</p><h3>Non-Determinism: Why Your Output Keeps Changing</h3><blockquote><strong><em>Non-determinism:</em></strong><em> Threads are non-deterministic. You don’t know which thread runs when, or which runs first. The execution order is unpredictable.</em></blockquote><p>The classic demo: two threads, one printing even numbers (2, 4, …, 100), the other printing odd numbers (1, 3, …, 99).</p><pre>Thread t1 = new Thread(() -&gt; {<br>    for (int i = 1; i &lt;= 100; i++)<br>        if (i % 2 == 0) System.out.println(&quot;T1 &quot; + i);<br>});</pre><pre>Thread t2 = new Thread(() -&gt; {<br>    for (int i = 1; i &lt;= 100; i++)<br>        if (i % 2 != 0) System.out.println(&quot;T2 &quot; + i);<br>});</pre><pre>t1.start();<br>t2.start();</pre><p>You might expect all evens, then all odds (since T1 starts first). What you actually get is a jumbled mix — T1 prints 2, 4, 6, 8, then T2 jumps in with 1, 3, 5, 7, 9, 11, 13, then T1 prints 10, and so on. <strong>Run it again and the output is completely different.</strong></p><h3>Why? The CPU Scheduler</h3><p>Threads are run by the CPU, and inside the CPU is a <strong>scheduling algorithm</strong> that decides which thread to pick and when. That decision is <em>not in your hands</em> as a developer. Scheduling strategies include Round Robin, Time Slicing, and Priority-based — among many others.</p><p>Thread execution order depends on:</p><ol><li>The <strong>scheduling algorithm</strong> of the OS/CPU</li><li><strong>System load</strong> — how busy the system is</li><li><strong>Hardware</strong> — how many cores you have (more cores = more parallelism)</li><li><strong>Thread creation time</strong> — when the OS <em>actually</em> creates the thread for the CPU (not when you create it in code)</li></ol><blockquote><strong><em>Why this is a real problem:</em></strong><em> Non-deterministic code is brutal to debug. A specific bug might appear once and then refuse to reproduce. That’s why multithreaded code demands careful writing and good practices — to minimize these errors.</em></blockquote><h3>The Thread Lifecycle</h3><p>We tend to imagine just two stages: created and started. But internally, a thread moves through several states.</p><pre>NEW<br> │  start()<br> ▼<br>RUNNABLE  ⇄  RUNNING (conceptual)<br> │  run() logic finishes<br> ▼<br>TERMINATED</pre><p><strong>NEW</strong> — The thread object is created (new Thread(...)), but start() hasn&#39;t been called. You&#39;ve only made an object in the heap; the OS knows nothing yet.</p><p><strong>RUNNABLE</strong> — After start(), you&#39;ve told the OS to create and start the thread. It&#39;s ready to run, waiting in the queue for the CPU.</p><p><strong>RUNNING (conceptual)</strong> — The thread currently executing on the CPU. Its run() method is being called. This is exactly why we don&#39;t call run() ourselves — it&#39;s invoked when the thread actually runs.</p><blockquote><strong><em>Important:</em></strong><em> In Java, RUNNABLE and RUNNING are treated as the </em><strong><em>same state</em></strong><em>, called RUNNABLE. RUNNING is just a mental model we build for understanding.</em></blockquote><p><strong>TERMINATED</strong> — The thread has finished all the work in run(). Once terminated, you can&#39;t restart it (hence the IllegalThreadStateException). No method call is needed to reach TERMINATED — it happens automatically when run() finishes.</p><p>But there are three more states, and they’re where things get interesting.</p><h3>BLOCKED: When Threads Fight Over Shared Resources</h3><p>Imagine two threads, T1 and T2, both running logic that touches a shared piece of data.</p><blockquote><strong><em>Example:</em></strong><em> A </em><em>Student object </em><em>S1 lives in the shared heap. T1&#39;s </em><em>run() does </em><em>S1.name = &quot;Aditya&quot;, while T2&#39;s does </em><em>S1.name = &quot;Rohit&quot;. Since the heap is shared, both threads share </em><em>S1. If they set the name simultaneously, the final value is unpredictable — could be &quot;Aditya&quot;, could be &quot;Rohit&quot;.</em></blockquote><p>That dangerous shared block of code is called a <strong>critical section</strong>. The fix is a <strong>lock</strong> — only one thread enters at a time.</p><pre>T1 enters the critical section → acquires the lock<br>   ↓<br>Other threads (T2, T3, T4) waiting outside CANNOT enter<br>   ↓<br>T1 finishes the critical section<br>   ↓<br>T1 releases the lock<br>   ↓<br>Another waiting thread enters and acquires the lock</pre><blockquote><strong><em>A subtle clarification:</em></strong><em> Locking doesn’t stop both threads from entering — it stops them from entering </em>at the same time<em>. We want changes to be deterministic: T1 then T2, or T2 then T1, but never both at once.</em></blockquote><p>So when one thread holds a lock and another tries to grab the same lock, the second one goes into the <strong>BLOCKED</strong> state. When the lock is released, it moves back to RUNNABLE.</p><p>BLOCKED isn’t only about locks, though. A thread also goes BLOCKED for an <strong>I/O task</strong> — say, waiting for user input. Until the input arrives, the thread can’t proceed, so it steps aside (BLOCKED) to let others run, then returns to RUNNABLE when the input shows up.</p><blockquote><strong><em>BLOCKED is entered when a thread wants to:</em></strong><em> acquire a lock held by another thread, </em>or<em> perform an I/O task. When the lock releases or the I/O completes, it returns to RUNNABLE.</em></blockquote><p><strong>Why are RUNNABLE and RUNNING one state?</strong> Because you can only start() a thread — you can&#39;t directly make it &quot;run.&quot; Whether a thread runs <em>now</em> is decided by the CPU scheduler and OS, not you. So &quot;ready to run&quot; and &quot;actually running&quot; are the same thing from your perspective. Java calls them both RUNNABLE.</p><h3>WAITING and TIMED WAITING</h3><p><strong>WAITING</strong> — A thread enters this state when you call wait() on it. It&#39;s useful for making two threads communicate. It comes back to RUNNABLE when you call notify() on it — it &quot;wakes up.&quot;</p><pre>RUNNABLE  — wait() →  WAITING<br>WAITING   — notify() →  RUNNABLE</pre><p><strong>TIMED WAITING</strong> — Here you make a thread wait for a <em>specific amount of time</em>. After the time’s up, it automatically returns to RUNNABLE. This happens via sleep(time), join(time), or wait(time).</p><h3>The stop() Method (Don’t Use It)</h3><blockquote><strong><em>stop() is deprecated.</em></strong><em> No matter which state a thread is in — NEW, RUNNABLE, BLOCKED, WAITING, or TIMED WAITING — calling </em><em>stop() sends it </em>directly<em> to TERMINATED.</em></blockquote><p>It’s not a good method, and you shouldn’t use it (the reasons come later in the series).</p><h3>The Full Lifecycle, at a Glance</h3><p>State When Entered How to Exit <strong>NEW</strong> Object created, start() not called start() → RUNNABLE <strong>RUNNABLE</strong> (incl. RUNNING) After start() — ready or running run() finishes → TERMINATED; lock/IO → BLOCKED; wait() → WAITING; sleep() → TIMED WAITING <strong>BLOCKED</strong> Waiting for a lock, or doing I/O Lock released / IO done → RUNNABLE <strong>WAITING</strong> wait() called notify() → RUNNABLE <strong>TIMED WAITING</strong> sleep(t), join(t), wait(t) Time finishes → RUNNABLE <strong>TERMINATED</strong> run() finishes, or stop() Cannot restart</p><blockquote><strong><em>Lock release rule:</em></strong><em> In the BLOCKED and WAITING states, a thread releases all the locks it holds (called </em>monitor locks<em>) for other threads. But the TIMED WAITING state does </em>not<em> release monitor locks.</em></blockquote><h3>Seeing States in Code</h3><p>Java’s Thread class has a State enum (Thread.State) holding all the states — NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED. (No RUNNING — it folds into RUNNABLE.) Use getState() to inspect a thread:</p><pre>Thread t1 = new Thread(() -&gt; {<br>    System.out.println(&quot;Name: &quot; + Thread.currentThread().getName());<br>});</pre><pre>System.out.println(t1.getState());   // NEW (before start)<br>t1.start();<br>System.out.println(t1.getState());   // RUNNABLE (just after start)</pre><p>To reliably see TERMINATED, you have to slow the main thread down so the worker can finish:</p><pre>t1.start();<br>System.out.println(t1.getState());   // RUNNABLE</pre><pre>try { Thread.sleep(2000); } catch (Exception e) {}  // main sleeps 2s</pre><pre>System.out.println(t1.getState());   // TERMINATED</pre><blockquote><em>Thread.sleep() throws a checked </em><em>InterruptedException, so it must be wrapped in try-catch.</em></blockquote><p>There’s even a clever trick to observe the <em>main</em> thread’s TIMED_WAITING state: grab the main thread’s reference first, then print its state from <em>inside</em> the worker thread (which runs in the background while main sleeps).</p><pre>Thread mainThread = Thread.currentThread();</pre><pre>Thread t1 = new Thread(() -&gt; {<br>    System.out.println(&quot;Name: &quot; + Thread.currentThread().getName());<br>    System.out.println(mainThread.getState());   // prints TIMED_WAITING<br>});</pre><h3>Wrapping Up</h3><p>We went from “how do I make a thread” all the way through its full life and death:</p><ul><li>Two creation routes — <strong>extend Thread</strong> vs <strong>implement Runnable</strong> — and why Runnable wins (separation of concern, reusability, multiple inheritance, lambdas).</li><li>Thread <strong>names</strong> are useful for logging; <strong>IDs</strong> are deprecated and meaningless.</li><li><strong>start() creates a new thread; </strong><strong>run() called directly just runs on the main thread.</strong></li><li>Threads are <strong>non-deterministic</strong> — the CPU scheduler, not you, decides the order.</li><li>The full <strong>lifecycle</strong>: NEW → RUNNABLE (with conceptual RUNNING) → possibly BLOCKED / WAITING / TIMED WAITING → TERMINATED.</li></ul><p>Next up: the important thread <em>methods</em> — sleep(), join(), yield(), interrupt(), and the rest — plus daemon threads, the background workers behind things like garbage collection.</p><p><em>If this cleared up thread creation and the lifecycle for you, give it a clap and follow along — the next part goes deep on thread methods and daemon threads.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a9647c3f03f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-Threading in Java — Part 1]]></title>
            <link>https://medium.com/@maheshsutar1328/multi-threading-in-java-part-1-29f4fa40ce76?source=rss-311fa431219c------2</link>
            <guid isPermaLink="false">https://medium.com/p/29f4fa40ce76</guid>
            <category><![CDATA[process]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[multithreading-in-java]]></category>
            <category><![CDATA[java-multithreading]]></category>
            <category><![CDATA[threading-in-java]]></category>
            <dc:creator><![CDATA[Maheshsutar]]></dc:creator>
            <pubDate>Tue, 26 May 2026 18:29:24 GMT</pubDate>
            <atom:updated>2026-05-26T18:29:24.681Z</atom:updated>
            <content:encoded><![CDATA[<h3>Multithreading in Java, Explained From Scratch: Programs, Processes, and Threads</h3><p><em>If you’ve ever wondered what actually happens when your Java code runs — and why “multithreading” is about so much more than just making things faster — this one’s for you.</em></p><p>Multithreading is one of those topics that shows up everywhere. It’s a favorite in interviews, and it’s unavoidable the moment you start building real-world applications. But most explanations jump straight into Thread objects and synchronized blocks without explaining the foundation.</p><p>So let’s not do that. Let’s build it from the ground up — starting with a question so basic it feels silly: <em>what is a program?</em> By the end, you’ll understand processes, threads, the JVM’s memory model, context switching, and the real difference between concurrency and parallelism.</p><p>No prior multithreading knowledge required. Let’s go.</p><h3>First, What Even Is Multithreading?</h3><p>Multithreading simply means having <strong>multiple threads</strong> executing the same program.</p><p>Normally, when you write code, it runs on a <strong>single thread</strong> called the <strong>main thread</strong>. This thread executes your instructions one by one, top to bottom. Sure, if statements and loops can split or repeat the flow, but the overall movement is sequential — instruction one, then two, then three.</p><p>With multithreading, you get additional threads (call them T1, T2, T3) working alongside the main thread, all executing your code together.</p><p>Here’s where most beginners go wrong:</p><blockquote><strong><em>The most common misconception:</em></strong><em> People assume the only benefit of multithreading is making code run faster. Speed is </em>a<em> benefit — but it’s actually the </em>least<em> important one. Multithreading offers far more.</em></blockquote><p>Think about your code editor. When you type in VS Code, multiple things happen at the same instant:</p><ul><li>Auto-complete suggestions pop up</li><li>Compilation errors get flagged with red underlines</li><li>The editor stays responsive while you keep typing</li></ul><p>These tasks run on different threads. One handles auto-complete, another checks for errors — and they run together. That responsiveness is multithreading in action, and it has nothing to do with raw speed.</p><p>To really get this, we need to climb up slowly. Three building blocks: <strong>Program → Process → Thread.</strong></p><h3>Building Block 1: What Is a Program?</h3><p>A program is just a <strong>set of instructions</strong> you write.</p><p>In Java, that might mean declaring a class with public static void main, declaring some variables, performing file I/O, or making a network call. All of it is just a set of instructions you want to execute, saved in a file with a .java extension — say, Demo.java.</p><p><strong>Here’s the key insight: a program just sits on your disk.</strong> Until you run it, it has no real meaning. It’s a file, lying there.</p><p>The journey from code to running program looks like this:</p><pre>You write Demo.java        →  source code on disk<br>javac Demo.java            →  compiles to bytecode<br>Demo.class is created      →  still just a file on disk!<br>java Demo                  →  finally runs</pre><p>Both Demo.java and Demo.class are <em>programs</em>. They&#39;re not doing anything yet. Think of the apps on your computer — Google Chrome, VS Code, Spotify. When they&#39;re not running, they&#39;re just icons sitting on your disk. Programs.</p><h3>Building Block 2: What Is a Process?</h3><p>Here’s the clean definition:</p><blockquote><strong><em>A program that is currently being executed is called a process.</em></strong></blockquote><p>So how does a program <em>become</em> a process? When you decide to run it, the <strong>Operating System</strong> picks it up from the disk and loads it into <strong>RAM</strong>. Once it’s loaded into RAM and actually running, it’s a process.</p><p>Why RAM, and not the disk directly? Because the CPU executes everything, and the CPU only talks to RAM — never directly to the hard disk. So anything that needs to run must first be brought into RAM.</p><p>The data flow looks like this:</p><pre>CPU  ⇄  Registers  ⇄  (Cache)  ⇄  RAM  ⇄  Disk (SSD/HDD)</pre><p>The CPU’s <strong>registers</strong> are tiny, blazing-fast storage for intermediate results. The CPU mainly interacts with RAM (with a cache layer in between we’ll ignore for now). And the Operating System is the one moving programs from disk into RAM.</p><p>The analogy is clean:</p><ul><li>Chrome, VS Code, Spotify <em>sitting on your computer</em> = <strong>programs</strong></li><li>Click the Chrome icon, it opens and runs = <strong>a process</strong></li></ul><h3>What a Process Needs to Run</h3><p>When a process runs, it needs three things:</p><ol><li><strong>RAM</strong> — a slice of your limited memory. If you have 8GB total, a process might grab 2GB.</li><li><strong>CPU time</strong> — the CPU has to allocate time slots to execute its instructions.</li><li><strong>Other resources</strong> — files for I/O, network access, and so on, all provided by the OS.</li></ol><p>And here’s a rule worth remembering:</p><blockquote><strong><em>Processes do not share memory.</em></strong><em> If Chrome uses 2GB and VS Code uses 2GB, neither can peek into the other’s memory. Every process works only with its own allocated RAM. One process can </em>never<em> look inside another’s memory.</em></blockquote><h3>Building Block 3: What Is a Thread?</h3><p>The textbook definition: a thread is the <strong>smallest sequence of instructions</strong> that can be executed by the CPU independently. It’s also called a <strong>lightweight process</strong>.</p><p>A process is a big chunk — your entire program loaded into RAM. We can divide that process into multiple threads.</p><blockquote><strong><em>Crucial point:</em></strong><em> When a Java program starts, even if you never create a thread yourself, Java </em>internally<em> creates one called the </em><strong><em>main thread</em></strong><em>. So a process always has at least one thread.</em></blockquote><p>You can then create more:</p><pre>Process P1<br>├── Main Thread<br>├── Thread T1<br>└── Thread T2</pre><p>Why “smallest sequence of instructions”? Because the CPU doesn’t execute an entire process at once — it always works with <strong>threads</strong>. If a CPU has a single core, it can run exactly one thread at a time. Modern CPUs (dual-core, octa-core, and beyond) can run multiple threads truly in parallel.</p><p>A <strong>core</strong> just tells you how many tasks the CPU can do at once. Single-core means one task at a time; octa-core means eight.</p><p>On a single core, the CPU might run the main thread for a moment, pause it, run T1, pause that, run T2, jump back to main — switching constantly. That switching has a name, and we’ll get to it.</p><h3>What Actually Happens When You Run java Demo</h3><p>Let’s trace it, step by step:</p><pre>1. OS creates a Process in RAM for your program<br>2. JVM loads inside that process<br>3. JVM uses the Class Loader to find your Main Class (the one with main())<br>4. JVM creates the Main Thread<br>5. JVM gives the Main Thread its own Stack + Program Counter<br>6. Code starts executing from the main method</pre><p>Inside the process, the <strong>JVM runs the show.</strong> It loads classes, runs the bytecode, manages memory (heap, method area, stack, program counter), and performs garbage collection.</p><blockquote><em>The Operating System’s only job is to </em>create<em> the process. After that, the JVM handles everything inside it.</em></blockquote><h3>Inside a Process: The Memory Model</h3><p>When a Java program runs, the JVM divides its memory into four main areas:</p><ul><li><strong>Heap</strong> — stores objects (shared by all threads)</li><li><strong>Method Area</strong> — stores class metadata (shared by all threads)</li><li><strong>Stack</strong> — stores method frames and local variables (<em>one per thread</em>)</li><li><strong>Program Counter (PC)</strong> — holds the current instruction address (<em>one per thread</em>)</li></ul><p>If you instead study threads in a generic Operating Systems course, you’ll see memory split as Data Segment, Code Segment, Heap, Stack, and Register. The two views map onto each other:</p><p>OS-Level (Generic) JVM-Level (Java) Data Segment + Code Segment Method Area Heap Heap Stack Stack Register Program Counter</p><p><strong>Why does the JVM insist on its own memory layout?</strong> Because Java is a <strong>platform-independent language.</strong> Java doesn’t want to depend on whatever OS it’s running on. So the JVM defines its own memory model — heap, method area, stack, PC — that behaves identically everywhere. It just takes RAM from whatever platform it’s on and carves out its own structure. (A plain C++ program wouldn’t have a JVM inside the process; it would use OS-managed memory directly.)</p><h3>Multiple Threads in One Process</h3><p>When several threads live inside a single process, here’s what’s shared and what isn’t:</p><p><strong>Shared by all threads:</strong></p><ul><li>Heap memory</li><li>Method Area</li></ul><p><strong>Unique to each thread:</strong></p><ul><li>Stack space</li><li>Program Counter</li></ul><p>So Main and T1 each get their own stack and PC, but they <em>share</em> the same heap and method area.</p><pre>Process<br>└── JVM<br>    ├── Heap (shared)<br>    ├── Method Area (shared)<br>    ├── Main Thread → [own Stack] [own PC]<br>    └── Thread T1   → [own Stack] [own PC]</pre><h3>How the CPU Runs Threads on a Single Core</h3><p>Picture a single-core CPU running a process with two threads: Main and T1.</p><p>The CPU fetches the current instruction from the thread’s Program Counter, finds the currently executing method in its stack, and runs instructions one at a time.</p><p>Take an expression like a = b + c * d. The CPU computes c * d first, stashes that intermediate result in its <strong>register</strong> (super fast), then adds b, and finally stores the result in a. Local variables and intermediate results live in the thread&#39;s <strong>stack</strong> as a stack frame.</p><h3>Context Switching: The Heart of It</h3><p>Here’s the move that makes single-core multithreading possible:</p><blockquote><strong><em>Context switching:</em></strong><em> When a single-core CPU has multiple threads to run, it can’t run them simultaneously — so it rapidly switches between them. Run Main for a fraction of a second, pause, run T1, pause, run Main again, and so on.</em></blockquote><p>But this raises a question: how does the CPU remember where it left off?</p><p>Imagine the main thread is running a loop from i = 0 to i = 100. After 50 iterations, the OS says &quot;switch to another thread.&quot; When the CPU eventually comes back, it needs to resume from iteration <em>51</em> — not start over at 0.</p><p>Here’s the mechanism:</p><ol><li>On a context switch, the CPU saves intermediate results into the thread’s <strong>stack</strong> (specifically, a region called the <strong>operand stack</strong>).</li><li>The <strong>Program Counter</strong> stores the address of the next instruction.</li><li>When the CPU returns to that thread, it reads the PC to know where to resume and reads the stack to recover the method state and intermediate results — then continues exactly where it left off.</li></ol><blockquote><em>This is </em>why<em> every thread needs its own stack and program counter: to save its individual context during switching.</em></blockquote><h3>Concurrent vs. Parallel: The Distinction That Matters</h3><p>This is the part people mix up constantly.</p><p><strong>Concurrent execution:</strong> Multiple threads are ready to work, but only <strong>one progresses at any given instant.</strong> Through rapid context switching, all of them make progress over time. On a single core, Main runs for 0.5s, then T1 for 0.5s, then Main again — and after a while, both have made progress (Main 50% done, T1 40% done). But at any single moment, only one is actually executing.</p><p>Even on a single core, the switching is so fast that it <em>feels</em> like things happen simultaneously — which is exactly why your IDE’s auto-complete and error-checking seem to run at the same time.</p><p><strong>Parallel execution (true parallelism):</strong> Multiple threads execute <em>genuinely simultaneously</em>, at the same instant. This requires <strong>multiple CPU cores.</strong> Core 1 runs Main, Core 2 runs T1 — no context switching needed.</p><p>The difference is stark when you look at timing. Say Main needs 3 seconds and T1 needs 3 seconds:</p><p>Scenario Total Time Why Concurrent (single core) 6 seconds Each runs separately (3 + 3) Parallel (two cores) 3 seconds Both run together, no switching</p><blockquote><strong><em>This is where multithreading’s “speed benefit” finally shows up</em></strong><em> — through true parallelism on multiple cores.</em></blockquote><p>But concurrency matters even without parallelism. For the IDE example, it doesn’t matter if auto-complete and error-checking are truly parallel — as long as context switching is fast enough that they <em>feel</em> simultaneous, the user experience is great. And in reality, no modern computer is single-core anyway, so you usually get both concurrency <em>and</em> parallelism.</p><h3>The Real-World Picture: Many Threads, Few Cores</h3><p>Now make it realistic. Say you have 5 threads (T1–T5) and 2 CPU cores. The threads might come from different processes:</p><ul><li>T1, T2 → Process P1 (Chrome)</li><li>T3, T4 → Process P2 (VS Code)</li><li>T5 → Process P3 (Spotify)</li></ul><p>Both cores run threads in parallel, <em>and</em> each core does context switching internally (because there are more threads than cores). A possible timeline:</p><pre>Core 1:  T1 → T3 → T1 → T2 → T3 → ...<br>Core 2:  T4 → T5 → T4 → T3 → T1 → ...</pre><p>Three things worth burning into memory:</p><ol><li><strong>The CPU doesn’t care about processes.</strong> To the CPU, processes don’t exist — only threads do. It just picks up threads and runs them.</li><li><strong>Which thread goes to which core is the OS’s decision,</strong> not yours.</li><li><strong>As a developer, your only control</strong> is deciding which threads are “runnable” (ready to run). The OS handles the scheduling.</li></ol><h3>Multitasking vs. Multithreading</h3><p>A classic interview question, and the distinction is genuinely important.</p><p><strong>Multithreading</strong> is a <em>programming</em> concept: multiple threads existing within a single process, running concurrently or in parallel. Example — a Java program with Main, T1, and T2.</p><p><strong>Multitasking</strong> is an <em>Operating System</em> concept: multiple <em>processes</em> running on your computer at once. Example — Chrome, VS Code, and Spotify all running together. The OS doesn’t care how many threads each process has internally.</p><p>Aspect Multithreading Multitasking Concept of Programming Operating System Deals with Threads within one process Multiple processes Example Multiple threads in one Java program Chrome + VS Code + Spotify together CPU’s view CPU runs threads CPU <em>still</em> runs threads</p><blockquote><strong><em>The unifying insight:</em></strong><em> At the end of the day, the CPU always runs threads — whether you call it multitasking or multithreading. Processes are just an OS-level grouping that’s completely invisible to the CPU.</em></blockquote><h3>Wrapping Up</h3><p>We covered a lot of ground from a deceptively simple starting question:</p><ul><li>A <strong>program</strong> is instructions sitting on disk.</li><li>A <strong>process</strong> is a program brought into RAM and running.</li><li>A <strong>thread</strong> is the smallest unit of execution the CPU works with.</li><li>The <strong>JVM</strong> manages memory inside the process, in a platform-independent way.</li><li><strong>Context switching</strong> is how a single core juggles multiple threads.</li><li><strong>Concurrency</strong> means making progress on many threads via switching; <strong>parallelism</strong> means truly running them at once on multiple cores.</li><li><strong>Multithreading</strong> is about threads in a process; <strong>multitasking</strong> is about processes in an OS — but the CPU only ever sees threads.</li></ul><p>This was the foundation. Next comes the fun part: actually <em>creating</em> threads in Java, walking through a thread’s lifecycle, and learning the methods that let you control them.</p><p><em>If this helped multithreading finally click for you, give it a clap and follow along — the next piece goes hands-on with thread creation in Java.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29f4fa40ce76" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>