<?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 Rajat Kumar on Medium]]></title>
        <description><![CDATA[Stories by Rajat Kumar on Medium]]></description>
        <link>https://medium.com/@rajatraghav7797?source=rss-d50c9c063b6f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_k3aLXbrWGVS01Tr.</url>
            <title>Stories by Rajat Kumar on Medium</title>
            <link>https://medium.com/@rajatraghav7797?source=rss-d50c9c063b6f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 09:08:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rajatraghav7797/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[The Node.js Version Bug That Taught Me How node_modules Actually Works]]></title>
            <link>https://medium.com/@rajatraghav7797/the-node-js-version-bug-that-taught-me-how-node-modules-actually-works-86d497b56787?source=rss-d50c9c063b6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/86d497b56787</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Rajat Kumar]]></dc:creator>
            <pubDate>Mon, 07 Sep 2026 18:57:28 GMT</pubDate>
            <atom:updated>2026-09-07T18:57:51.541Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Or: why running two apps on two Node versions on the same machine broke everything, and what I learned digging all the way down.</em></h4><h3>The problem</h3><p>I had two Node.js services running locally:</p><ul><li>One depends on node-rdkafka, which needs <strong>Node 21</strong>.</li><li>The other is an older service that only runs on <strong>Node 16</strong>.</li></ul><p>Simple enough — switch Node versions with nvm use depending on which app I&#39;m running, right?</p><p>Except every time I switched, one of the two apps broke with some variation of this error:</p><pre>Error: The module &#39;.../rdkafka.node&#39;<br>was compiled against a different Node.js version using<br>NODE_MODULE_VERSION 108. This version of Node.js requires<br>NODE_MODULE_VERSION 115.</pre><p>Run on Node 16 → the Node-21-compiled binary fails. Switch to Node 21 → the Node-16-compiled binary fails, just in the other direction.</p><p>My first fix was the obvious one: delete node_modules, reinstall, problem gone — for whichever app I&#39;d just switched to. But that&#39;s a band-aid, not an understanding. So I went and actually traced through what npm install does, end to end, to figure out <em>why</em> this happens and what the correct long-term fix is. This article is that deep dive.</p><h3>1. The core files, and what each one actually does</h3><p>File / Folder Purpose package.json Project manifest — name, scripts, <strong>dependency ranges</strong>, engines package-lock.json The exact resolved dependency tree — pinned versions + integrity hashes node_modules/ The installed packages on disk (not usually committed to git) .nvmrc (recommended) The team-standard Node version, e.g. 18.20.4</p><p>Here’s a package.json in the style we use at work:</p><pre>{<br>  &quot;name&quot;: &quot;@freighttiger/ptl-service-v2&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;node source/main.js&quot;,<br>    &quot;test&quot;: &quot;nyc mocha test/* --require test/setup.js --exit&quot;<br>  },<br>  &quot;engines&quot;: {<br>    &quot;node&quot;: &quot;&gt;=10.15.0&quot;<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;express&quot;: &quot;^4.16.4&quot;,<br>    &quot;sequelize&quot;: &quot;^6.37.2&quot;,<br>    &quot;mysql2&quot;: &quot;^1.6.5&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;mocha&quot;: &quot;^10.4.0&quot;<br>  }<br>}</pre><p>The key idea that trips people up: <strong>package.json defines allowed version <em>ranges</em>, not exact versions.</strong> Two people who clone the same repo on different days can end up with different actual versions installed — unless there&#39;s a lockfile involved (more on that shortly).</p><h3>2. What actually happens from npm init to first run</h3><h3>Step 1 — Initialize the project</h3><pre>mkdir ptl-service-v2<br>cd ptl-service-v2<br>npm init -y</pre><p>This creates package.json and nothing else. At this point there are:</p><ul><li>no dependencies installed</li><li>no node_modules</li><li>no package-lock.json</li></ul><h3>Step 2 — Install dependencies</h3><pre>npm install express sequelize mysql2<br>npm install --save-dev mocha chai</pre><p>Here’s what npm is actually doing behind that one command:</p><ol><li>Reads package.json</li><li>Resolves version ranges using semver rules</li><li>Builds the full dependency graph — direct dependencies <em>and</em> their transitive dependencies</li><li>Downloads the package tarballs (.tgz files) from the npm registry</li><li>Verifies each download’s integrity via checksum/hash</li><li>Extracts each tarball into node_modules/</li><li>Runs any install scripts the package defines (preinstall, install, postinstall)</li><li>Updates package.json&#39;s dependency entries</li><li>Writes or updates package-lock.json with the exact resolved versions</li></ol><p>Step 6 and step 7 are the two steps that matter most for the bug I hit — keep them in mind.</p><h3>3. Semver rules — how npm decides which version to install</h3><p>Versions follow MAJOR.MINOR.PATCH — e.g. 1.6.5. The prefix in package.json decides how much npm is allowed to move that version forward on your behalf:</p><p>Specifier Meaning Example range for 1.6.5 1.6.5 (exact) Only that version 1.6.5 ~1.6.5 (tilde) Patch updates only &gt;=1.6.5 &lt;1.7.0 ^1.6.5 (caret) Minor + patch updates &gt;=1.6.5 &lt;2.0.0</p><p><strong>Worked example:</strong> say package.json says &quot;mysql2&quot;: &quot;^1.6.5&quot;, and the npm registry currently has 1.6.5, 1.7.0, 1.11.0, and 2.0.0 published.</p><ul><li>Allowed by ^1.6.5: anything from 1.6.5 up to 1.11.0</li><li>Not allowed: 2.0.0 (that&#39;s a major bump)</li></ul><p>npm picks the <em>latest allowed</em> version — say 1.11.0 — installs it, and writes that exact version into the lockfile.</p><h3>4. What’s actually inside a “tarball download”</h3><p>A tarball is just a compressed archive (.tgz) of a package&#39;s source code. For mysql2@1.11.0, npm is quite literally fetching a URL like:</p><pre>https://registry.npmjs.org/mysql2/-/mysql2-1.11.0.tgz</pre><p>Then it:</p><ol><li>Verifies the checksum against what the registry claims</li><li>Extracts the contents into node_modules/mysql2/</li><li>Repeats this entire process for every transitive dependency in the graph</li></ol><p>Nothing magic — it’s downloading a zip file and unpacking it, over and over, for potentially hundreds of packages.</p><h3>5. Why package-lock.json exists at all</h3><p>Think of package-lock.json as <strong>the reproducibility contract</strong> for your project. It stores:</p><ul><li>Exact package versions (not ranges)</li><li>The full dependency tree structure</li><li>Resolved download URLs and integrity hashes</li><li>The lockfile format version itself (our repo uses lockfileVersion: 2)</li></ul><p><strong>Without a lockfile:</strong> two developers running npm install on different days can end up with different transitive dependency versions, because npm re-resolves ranges against whatever is currently published.</p><p><strong>With a lockfile:</strong> everyone gets the exact same tree, every time, regardless of what’s been published to the registry since.</p><h3>6. npm install vs npm ci — these are not interchangeable</h3><p>Command Use case Behavior npm install Local development, adding/updating deps May update the lockfile if needed npm ci CI/CD and clean reproducible installs Strict install <em>from</em> the lockfile — fails on any mismatch</p><p><strong>Recommended usage:</strong></p><ul><li>Right after cloning locally → npm ci</li><li>In your CI pipeline → npm ci</li><li>Adding a new package → npm install &lt;pkg&gt;, then commit <em>both</em> package.json and the updated lockfile</li></ul><p>npm ci is stricter on purpose — it refuses to &quot;helpfully&quot; resolve anything for you. It either matches the lockfile exactly, or it fails loudly. That&#39;s exactly the behavior you want in CI.</p><h3>7. How node_modules actually gets resolved at runtime</h3><p>When your code runs:</p><pre>const express = require(&#39;express&#39;);</pre><p>Node resolves that module by searching, in order:</p><ol><li>./node_modules/express</li><li>../node_modules/express</li><li>Continuing upward through parent directories</li></ol><p>npm tries to <strong>flatten</strong> most dependencies into a single top-level node_modules folder whenever it can. Nested node_modules folders only appear when there&#39;s a genuine version conflict that forces two different versions of the same package to coexist.</p><h3>8. Native modules — this is where my actual bug lived</h3><p>This is the part of the puzzle that most day-to-day Node work never touches, but it’s exactly what caused my version-mismatch bug.</p><p>Some packages — mysql2 and, critically, rdkafka — aren&#39;t pure JavaScript. They ship compiled C/C++ binaries alongside the JS.</p><p><strong>At install time</strong>, npm may run node-gyp build steps that <strong>compile a </strong><strong>.node binary specifically for your current Node ABI, OS, and CPU architecture.</strong></p><p><strong>Why the Node version matters so much:</strong> a native binary compiled against Node 16 is tied to that Node version’s Application Binary Interface (ABI). Try to load it from a Node 21 process, and you get exactly the error I started with:</p><pre>Error: The module &#39;.../mysql2.node&#39;<br>was compiled against a different Node.js version using<br>NODE_MODULE_VERSION 108. This version of Node.js requires<br>NODE_MODULE_VERSION 115.</pre><p>NODE_MODULE_VERSION is literally the ABI version number. It&#39;s not a bug in the module — it&#39;s the binary doing exactly what it&#39;s designed to do: refuse to load against an ABI it wasn&#39;t built for.</p><p><strong>The fix:</strong></p><pre>rm -rf node_modules<br>npm ci<br># only if still needed after a clean install<br>npm rebuild</pre><p><strong>Two things worth remembering:</strong></p><ul><li>Always delete and reinstall node_modules after switching Node versions.</li><li>Do <strong>not</strong> delete package-lock.json for a normal Node version switch — the lockfile isn&#39;t the problem, the compiled binaries are.</li></ul><h3>9. npm lifecycle scripts — the hidden automation inside install</h3><p>Packages can define scripts that run automatically at specific points:</p><ul><li>preinstall, install, postinstall</li><li>prestart, start, poststart</li></ul><p>So npm install is never <em>just</em> &quot;extract files into a folder.&quot; For native packages, the install script is precisely where that node-gyp compilation step happens. This is also why a &quot;simple&quot; install can sometimes take much longer for packages like rdkafka than for a pure-JS package of similar size — it&#39;s compiling, not just downloading.</p><h3>10. Running the application</h3><pre>npm start</pre><p>For a repo where package.json defines &quot;start&quot;: &quot;node source/main.js&quot;, here&#39;s the actual chain of events:</p><ol><li>npm reads the scripts section of package.json</li><li>It spawns a Node process</li><li>Node loads the entrypoint file</li><li>The require() chain pulls in app modules and their dependencies from node_modules</li><li>The app initializes — config, DB connections, Kafka clients, routes, etc.</li></ol><p>If any dependency in that chain includes a native binary compiled for the wrong Node version, this is the exact point where it explodes.</p><h3>11. What happens when you switch Node versions (three scenarios)</h3><p><strong>Scenario A — switch Node, keep the old </strong><strong>node_modules:</strong> Possible outcomes: it might just work (if nothing native is involved), it might crash with a NODE_MODULE_VERSION mismatch, or you might get vague &quot;missing module&quot; / runtime errors.</p><p><strong>Scenario B — switch Node, reinstall dependencies (the correct approach):</strong></p><pre>node -v<br>rm -rf node_modules<br>npm ci<br>npm test<br>npm start</pre><p><strong>Scenario C — switch Node <em>and</em> switch npm’s major version:</strong> The lockfile itself may get reformatted or restructured. Always review the lockfile diff carefully before committing in this case — a huge unexpected diff here is a signal worth investigating, not just accepting.</p><h3>12. The team policy I ended up writing down</h3><p>Once I understood <em>why</em> this breaks, the fix stopped being “reinstall and hope” and became an actual policy:</p><p><strong>1. Pin the Node version per project</strong> Add a .nvmrc file (e.g. 18.20.4) and use the same Node version across local, CI, and Docker.</p><p><strong>2. Always commit the lockfile</strong> package-lock.json should always be committed — never gitignored.</p><p><strong>3. Use </strong><strong>npm ci in CI, always</strong> Deterministic installs, no surprises.</p><p><strong>4. Tighten your </strong><strong>engines field</strong> Avoid loose ranges like &gt;=10.15.0 — prefer an explicit LTS version so mismatches surface early instead of silently.</p><p><strong>5. Reinstall on every Node switch</strong> Never reuse node_modules across a Node major version change — this is the single rule that would have saved me the whole debugging session.</p><p><strong>6. Review lockfile diffs in every PR</strong> A large, unexpected lockfile diff is often a sign of accidental dependency drift, not just noise to skip past.</p><h3>13. Copy-paste onboarding commands</h3><p>For anyone joining a project and wanting to start clean:</p><pre># 1) Use the team&#39;s Node version<br>nvm install<br>nvm use<br><br># 2) Verify versions<br>node -v<br>npm -v<br><br><br># 3) Clean install from the lockfile<br>rm -rf node_modules<br>npm ci<br><br><br># 4) Validate<br>npm test<br>npm start</pre><h3>14. Troubleshooting playbook</h3><p><strong>NODE_MODULE_VERSION mismatch</strong> Cause: a native module was compiled for a different Node version. Fix: rm -rf node_modules &amp;&amp; npm ci &amp;&amp; npm rebuild</p><p>**npm ci fails: &quot;can only install with an existing package-lock.json&quot;** Cause: there&#39;s no lockfile yet. Fix: run npm install` once, then commit the generated lockfile.</p><p><strong>npm ci fails due to a </strong><strong>package.json / lockfile mismatch</strong> Cause: package.json changed but the lockfile wasn&#39;t updated to match. Fix: run npm install, then commit the updated lockfile.</p><p><strong>App works locally but fails in CI</strong> Check, in order: Node version mismatch between local and CI, whether CI is using npm install instead of npm ci, and whether the CI image has the build tools native modules need (node-gyp requires a C++ compiler and Python).</p><h3>15. A concrete example with our actual dependency style</h3><p>Given:</p><pre>&quot;sequelize&quot;: &quot;^6.37.2&quot;</pre><p>The first install might resolve this to, say, 6.37.3. The lockfile then pins that exact version along with the full resolved tree underneath it. From then on, npm ci will <strong>always</strong> install exactly what the lockfile says — regardless of any newer 6.37.x releases that show up on the registry later. That&#39;s the entire point of the lockfile: it freezes the tree at the moment you last ran a real npm install.</p><h3>16. Quick reference</h3><ul><li>package.json = allowed dependency ranges + scripts</li><li>package-lock.json = the exact install blueprint</li><li>node_modules = the actual installed artifacts on disk</li><li>^ = minor + patch updates allowed within the same major version</li><li>~ = patch updates only</li><li>Native modules need a rebuild whenever the Node version changes</li><li>After a Node switch: reinstall node_modules, keep the lockfile</li><li>CI should always use npm ci, never npm install</li></ul><h3>Closing thought</h3><p>The bug itself took five minutes to fix once I knew what was wrong. Understanding <em>why</em> it happened took a lot longer — but it’s the kind of understanding that pays for itself the next time someone on the team hits a cryptic NODE_MODULE_VERSION error and doesn&#39;t know whether to panic. Now there&#39;s a doc for that.</p><p>If you’ve hit something similar — multiple Node versions, native modules, mysterious ABI errors — I’d genuinely like to hear how you diagnosed it. There’s usually more than one way people arrive at the same fix.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86d497b56787" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node.js: The Complete Picture]]></title>
            <link>https://medium.com/@rajatraghav7797/node-js-the-complete-picture-97b2fb3fbb51?source=rss-d50c9c063b6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/97b2fb3fbb51</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[javascript-event-loop]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Rajat Kumar]]></dc:creator>
            <pubDate>Mon, 07 Sep 2026 18:30:37 GMT</pubDate>
            <atom:updated>2026-09-07T18:30:57.287Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 1 — What Node.js Actually Is (and the Lie That Trips Up Every Interview)</h4><h3>The claim you’ve heard a hundred times</h3><blockquote><strong><em>“Node.js is single-threaded.”</em></strong></blockquote><p>You’ve probably said it in an interview. The interviewer nodded. Everyone moved on. But here’s the question that should bother you:</p><p><strong>If Node.js is single-threaded, how can one Node.js process handle thousands of concurrent connections?</strong></p><p>The answer isn’t that Node somehow makes JavaScript run on thousands of threads.</p><p>The real answer is more interesting:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O-k0gqfBGEzZMdwYtu5BAg.png" /></figure><blockquote><strong><em>JavaScript execution is single-threaded, but the runtime surrounding JavaScript can perform and coordinate many operations concurrently.</em></strong></blockquote><p>To understand that properly, we need to start one layer below Node.js itself.</p><h3>1. First: What is JavaScript?</h3><p>JavaScript is a <strong>programming language</strong>.</p><p>When you write:</p><pre>const x = 10;<br>console.log(x + 20);</pre><p>JavaScript itself doesn’t know anything about:</p><ul><li>files</li><li>TCP sockets</li><li>HTTP servers</li><li>operating systems</li><li>CPUs</li><li>databases</li><li>DNS</li></ul><p>Those things aren’t part of the JavaScript language. So who actually executes JavaScript? That’s where the <strong>JavaScript engine</strong> comes in.</p><h3>2. V8: The JavaScript Engine</h3><p>Node.js uses <strong>V8</strong>, Google’s JavaScript engine. V8 is responsible for executing JavaScript.</p><p>Conceptually:</p><pre>JavaScript Code<br>              │<br>              ▼<br>        ┌───────────┐<br>        │    V8     │<br>        │           │<br>        │ Parse     │<br>        │ Compile   │<br>        │ Execute   │<br>        │ GC        │<br>        └───────────┘</pre><p>V8 handles things such as:</p><ul><li>parsing JavaScript</li><li>compiling JavaScript</li><li>executing JavaScript</li><li>managing the JavaScript heap</li><li>garbage collection</li><li>JavaScript objects and functions</li></ul><p>But here’s the important question:</p><h3>Does V8 know what fs.readFile() means?</h3><p>No.</p><p>If you write:</p><pre>fs.readFile(&quot;data.txt&quot;, callback);</pre><p>V8 doesn’t inherently understand:</p><blockquote><em>“I should open a file on the operating system.”</em></blockquote><p>fs isn&#39;t a magical V8 feature. It is functionality <strong>provided by Node.js</strong>. And this distinction is fundamental.</p><h3>3. JavaScript Engine vs Runtime</h3><p>This is one of the most important concepts to understand. A <strong>JavaScript engine</strong> executes JavaScript. A <strong>JavaScript runtime</strong> provides the environment in which JavaScript runs.</p><p>For example:</p><pre>                 JavaScript<br>                       │<br>             ┌─────────┴─────────┐<br>             │                   │<br>          Browser              Node.js<br>             │                   │<br>          V8 engine            V8 engine<br>             │                   │<br>        Browser APIs         Node.js APIs<br>             │                   │<br>        DOM, Web APIs       fs, net, http,<br>                            crypto, process...</pre><p>Both Chrome and Node.js can use V8. But they provide very different environments around it. A browser gives JavaScript things like:</p><pre>document<br>window<br>fetch()<br>localStorage</pre><p>Node.js gives JavaScript things like:</p><pre>fs<br>http<br>net<br>process<br>Buffer<br>crypto</pre><p>So:</p><blockquote><strong><em>V8 executes JavaScript. Node.js provides the server-side runtime around V8.</em></strong></blockquote><h3>4. So What Exactly Is Node.js?</h3><p>A useful mental model is:</p><pre>                 Node.js Runtime<br>                         │<br>          ┌──────────────┼──────────────┐<br>          │              │              │<br>          ▼              ▼              ▼<br>         V8        Node.js APIs     Native layer<br>          │              │              │<br>          │              │        ┌─────┼─────┐<br>          │              │        │     │     │<br>          │              │        ▼     ▼     ▼<br>          │              │      libuv  OS   OpenSSL<br>          │              │<br>          └──────────────┴──────────────┘</pre><p>There isn’t a separate “Node.js language.” Node.js is a <strong>runtime environment</strong> that embeds V8 and provides additional capabilities needed to build server-side applications.</p><p>Those capabilities are implemented through a combination of:</p><ul><li>JavaScript code</li><li>native C/C++ code</li><li>Node.js internal APIs</li><li>libuv</li><li>operating-system facilities</li><li>libraries such as OpenSSL</li></ul><p>And this brings us to an important term: <strong>Bindings</strong></p><h3>5. What Are Bindings?</h3><p>The word <strong>binding</strong> sounds complicated, but the idea is simple. JavaScript and native code live in different worlds. Suppose Node.js has some native C++ functionality that JavaScript needs to access.</p><p>Something needs to provide the bridge:</p><pre>JavaScript world<br>      │<br>      │<br>      ▼<br>   Binding<br>      │<br>      │<br>      ▼<br>Native C/C++ world</pre><p>That bridge is broadly what we mean by a <strong>native binding</strong>. For example, conceptually:</p><pre>JavaScript<br>    │<br>    ▼<br>Node.js API<br>    │<br>    ▼<br>Native binding / native implementation<br>    │<br>    ├──────────► libuv<br>    │<br>    ├──────────► OS APIs<br>    │<br>    ├──────────► OpenSSL<br>    │<br>    └──────────► Other native functionality</pre><h3>Important:</h3><p><strong>A binding is not specifically a connection to libuv. </strong>That’s a common misconception. Bindings allow Node’s JavaScript-facing APIs to interact with native implementations.</p><p>Depending on the API, that native implementation may interact with:</p><ul><li>libuv</li><li>operating-system APIs</li><li>OpenSSL</li><li>V8</li><li>other native components</li></ul><p>So don’t memorize:</p><blockquote><em>Binding = connection to libuv</em></blockquote><p>Instead remember:</p><blockquote><strong><em>Binding = bridge between JavaScript-facing Node functionality and native code.</em></strong></blockquote><h3>6. Let’s Follow fs.readFile() All the Way Down</h3><p>Now we can understand something much more interesting. Suppose you write:</p><pre>const fs = require(&#39;fs&#39;);<br><br>fs.readFile(&#39;data.txt&#39;, (err, data) =&gt; {<br>    console.log(data);<br>});<br>console.log(&#39;Done&#39;);</pre><p>What actually happens? Don’t imagine that V8 itself suddenly starts reading the file. Let’s follow the request.</p><h4>Step 1: V8 executes your JavaScript</h4><p>V8 is executing:</p><pre>fs.readFile(&#39;data.txt&#39;, callback);</pre><p>V8 knows how to execute the JavaScript instructions. But the actual file-system operation is provided by Node.js.</p><h4>Step 2: Node.js receives the API call</h4><p>The fs API is part of Node.js. Node.js determines what needs to happen for readFile(). The implementation can involve JavaScript-level Node internals and native functionality.</p><p>Eventually, native code may become involved.</p><p>Conceptually:</p><pre>Your JavaScript<br>      │<br>      ▼<br>Node.js fs API<br>      │<br>      ▼<br>Native implementation</pre><h4>Step 3: Native code interacts with the async infrastructure</h4><p>For operations that use libuv, Node’s native layer can hand work to libuv. Conceptually:</p><pre>JavaScript<br>    │<br>    ▼<br>Node.js API<br>    │<br>    ▼<br>Native layer<br>    │<br>    ▼<br>  libuv</pre><p>At this point, the important thing is: <strong>Your JavaScript thread doesn’t sit there waiting for the file.</strong></p><h4>Step 4: The operation continues outside your JavaScript execution</h4><p>Depending on the operation and operating system, libuv may:</p><ul><li>use an OS facility for asynchronous I/O, or</li><li>use its worker thread pool when an operation needs blocking system calls underneath.</li></ul><p>For example, filesystem operations commonly use libuv’s thread pool. So conceptually:</p><pre>                    ┌───────────────┐<br>                    │ JavaScript    │<br>                    │ thread        │<br>                    └───────┬───────┘<br>                            │<br>                       starts I/O<br>                            │<br>                            ▼<br>                    ┌───────────────┐<br>                    │     libuv     │<br>                    └───────┬───────┘<br>                            │<br>                    ┌───────┴────────┐<br>                    │                │<br>                    ▼                ▼<br>              OS async I/O      libuv worker<br>                                  thread pool</pre><p>The exact path depends on the API. This is why saying:</p><blockquote><em>“Everything asynchronous in Node goes through the thread pool”</em></blockquote><p>is also wrong.</p><p>Network sockets, for example, can use OS-level readiness mechanisms such as epoll on Linux or kqueue on macOS.</p><h3>7. What Does “Registering a Callback” Actually Mean?</h3><p>When you write:</p><pre>fs.readFile(&#39;data.txt&#39;, callback);</pre><p>you’re effectively saying:</p><blockquote><em>“Start this operation, and when the result is ready, I want this function to be executed.”</em></blockquote><p>The callback doesn’t execute immediately. Instead, Node/libuv keeps enough information to associate the eventual completion with your callback.</p><p>Conceptually:</p><pre>fs.readFile(...)<br>      │<br>      ├── Start operation<br>      │<br>      └── Remember callback<br>               │<br>               ▼<br>          I/O in progress<br>               │<br>               │<br>          ... time passes ...<br>               │<br>               ▼<br>          Operation completes<br>               │<br>               ▼<br>       Callback becomes eligible<br>               │<br>               ▼<br>          Event loop<br>               │<br>               ▼<br>              V8<br>               │<br>               ▼<br>        callback executes</pre><p>This is the key idea behind Node’s asynchronous programming model.</p><h3>8. So What Is libuv?</h3><p>Now that we’ve seen the complete path, we can properly define libuv.</p><p><strong>libuv is a native library used by Node.js to provide cross-platform asynchronous I/O infrastructure.</strong></p><p>It provides things such as:</p><ul><li>the event loop</li><li>timers</li><li>asynchronous networking</li><li>filesystem operations through its APIs</li><li>DNS-related facilities</li><li>a worker thread pool for certain operations</li></ul><p>A simplified view:</p><pre>                 Node.js<br>                    │<br>              Native layer<br>                    │<br>                    ▼<br>                  libuv<br>             ┌──────┴──────┐<br>             │             │<br>             ▼             ▼<br>        Event Loop     Worker Pool<br>             │<br>             ▼<br>          OS APIs</pre><p>But here’s another distinction we need to make.</p><h3>9. libuv ≠ Event Loop</h3><p>People often use these terms interchangeably. They’re related, but they aren’t the same thing.</p><h3>libuv</h3><p>A native library providing asynchronous infrastructure.</p><h3>Event loop</h3><p>A mechanism inside libuv that repeatedly checks for work that is ready to be processed and coordinates callbacks. Think of libuv as the <strong>toolkit/infrastructure</strong>. Think of the event loop as one of the <strong>central mechanisms inside that toolkit</strong>.</p><h3>10. The Event Loop</h3><p>The event loop is responsible for coordinating work that is ready to continue.</p><p>A simplified model looks like this:</p><pre>                ┌──────────────────┐<br>                │   JavaScript     │<br>                │    execution     │<br>                └────────┬─────────┘<br>                         │<br>                         ▼<br>                 ┌───────────────┐<br>                 │  Event Loop   │<br>                 └───────┬───────┘<br>                         │<br>              ┌──────────┴──────────┐<br>              │                     │<br>              ▼                     ▼<br>        OS async I/O          libuv worker<br>                              thread pool<br>              │                     │<br>              └──────────┬──────────┘<br>                         │<br>                    completion<br>                         │<br>                         ▼<br>                  Event Loop<br>                         │<br>                         ▼<br>                        V8<br>                         │<br>                         ▼<br>                  Callback runs</pre><p>The event loop isn’t executing JavaScript simultaneously on hundreds of threads. Instead, it determines:</p><blockquote><em>“Which JavaScript callback is ready to run next?”</em></blockquote><p>Then V8 executes that callback.</p><h3>11. Now We Can Understand “Single-Threaded”</h3><p>We’re finally ready to revisit the famous statement:</p><blockquote><strong><em>“Node.js is single-threaded.”</em></strong></blockquote><p>It’s incomplete.</p><p>A more accurate statement is:</p><blockquote><strong><em>JavaScript execution in a Node.js process is single-threaded.</em></strong></blockquote><p>Your JavaScript code runs on one main thread:</p><pre>        JavaScript<br>             │<br>             ▼<br>            V8<br>             │<br>        ONE execution<br>           thread</pre><p>But the runtime surrounding it can involve other threads and OS mechanisms:</p><pre>                    Node.js<br>                       │<br>             ┌─────────┴─────────┐<br>             │                   │<br>             ▼                   ▼<br>       JS execution          Native/runtime<br>        one thread              machinery<br>                                 │<br>                       ┌─────────┴─────────┐<br>                       │                   │<br>                       ▼                   ▼<br>                  OS async I/O        Worker pool<br>                                      multiple threads</pre><p>So: <strong>One JavaScript execution thread ≠ one thread in the entire Node.js process.</strong></p><h3>12. Concurrency Does Not Mean Parallel JavaScript</h3><p>This distinction is critical.</p><p>Suppose three requests arrive:</p><pre>Request A ── waiting for DB<br>Request B ── waiting for file<br>Request C ── waiting for network</pre><p>Node doesn’t need three JavaScript threads.</p><p>It can do:</p><pre>ONE JS THREAD</pre><pre>A starts ──► register I/O ──► continue</pre><pre>B starts ──► register I/O ──► continue</pre><pre>C starts ──► register I/O ──► continue</pre><p>While those operations are waiting:</p><pre>Outside JS execution</pre><pre>       A ───────────► I/O<br>       B ───────────► I/O<br>       C ───────────► I/O</pre><p>When something completes:</p><pre>A completes<br>     │<br>     ▼<br>callback becomes ready<br>     │<br>     ▼<br>event loop<br>     │<br>     ▼<br>V8 executes callback</pre><p>That’s <strong>concurrency</strong>. It does not mean:</p><pre>Thread 1 → JavaScript A<br>Thread 2 → JavaScript B<br>Thread 3 → JavaScript C</pre><p>That’s parallel execution, and that’s not how ordinary Node.js JavaScript execution works.</p><h3>13. Now Let’s Break the Model</h3><p>Here’s a tiny HTTP server:</p><pre>const http = require(&#39;http&#39;);<br><br>let requestCount = 0;<br>const server = http.createServer((req, res) =&gt; {<br>    requestCount++;<br>    const id = requestCount;<br>    if (req.url === &#39;/block&#39;) {<br>        console.log(`[Request ${id}] /block received`);<br>        const start = Date.now();<br>        // Simulate CPU-heavy synchronous work<br>        while (Date.now() - start &lt; 3000) {<br>            // Busy wait<br>        }<br>        console.log(`[Request ${id}] /block finished`);<br>        res.end(`Blocked for 3s (request #${id})\n`);<br>        return;<br>    }<br>    console.log(`[Request ${id}] /fast received`);<br>    res.end(`Fast response (request #${id})\n`);<br>});<br>server.listen(3000, () =&gt; {<br>    console.log(&#39;Server listening on 3000&#39;);<br>});</pre><p>Now send:</p><pre>Request 1 → /block<br>Request 2 → /fast<br>Request 3 → /fast</pre><p>You might expect /fast to respond immediately because Node.js is supposed to handle concurrent requests. But it doesn’t. Why?</p><p>Because /block is doing:</p><pre>while (Date.now() - start &lt; 3000) {}</pre><p>That is <strong>synchronous JavaScript execution</strong>. The JavaScript thread is occupied.</p><h3>14. What Happens Internally?</h3><p>Conceptually:</p><pre>Request 1<br>   │<br>   ▼<br>Node invokes JS callback<br>   │<br>   ▼<br>while (...) {}<br>   │<br>   │  3 seconds<br>   │<br>   ▼<br>JS thread remains occupied</pre><p>Meanwhile:</p><pre>Request 2 ── waiting<br>Request 3 ── waiting</pre><p>The event loop cannot magically execute their JavaScript callbacks on another thread.</p><p>Why?</p><p>Because there is only one JavaScript execution thread.</p><p>So:</p><pre>ONE JS THREAD<br>             │<br>             ▼<br>       /block callback<br>             │<br>        ███████████<br>        CPU busy<br>        ███████████<br>             │<br>             ▼<br>      /fast callback<br>             │<br>             ▼<br>      /fast callback</pre><p>The /fast requests only get their turn after /block finishes.</p><h3>15. Now Make the Wait Asynchronous</h3><p>Change /block to:</p><pre>if (req.url === &#39;/block&#39;) {<br>    console.log(`[Request ${id}] /block received`);<br>    setTimeout(() =&gt; {<br>        console.log(`[Request ${id}] /block finished`);<br>        res.end(`Done after 3s (request #${id})\n`);<br>    }, 3000);<br>    return;<br>}</pre><p>Now something interesting happens. setTimeout() doesn&#39;t keep the JavaScript thread busy for three seconds. Instead, Node registers the timer and returns. Conceptually:</p><pre>/block<br>  │<br>  ▼<br>setTimeout(...)<br>  │<br>  ├── register timer<br>  │<br>  └── return immediately<br>          │<br>          ▼<br>     JS thread free<br>          │<br>          ▼<br>      /fast request<br>          │<br>          ▼<br>       responds</pre><p>Three seconds later:</p><pre>Timer expires<br>     │<br>     ▼<br>Event loop notices callback is ready<br>     │<br>     ▼<br>V8 executes callback<br>     │<br>     ▼<br>Response sent</pre><p>This is the fundamental Node.js model.</p><h3>16. The Mental Model to Keep</h3><p>Put all the pieces together:</p><pre>                      Node.js Runtime<br>                               │<br>                 ┌─────────────┴─────────────┐<br>                 │                           │<br>                 ▼                           ▼<br>              V8 / JS                  Node.js APIs<br>                 │                           │<br>                 │                    native implementation<br>                 │                           │<br>                 │                       bindings<br>                 │                           │<br>                 │                           ▼<br>                 │                         libuv<br>                 │                    ┌──────┴──────┐<br>                 │                    │             │<br>                 │                    ▼             ▼<br>                 │              Event Loop      Worker Pool<br>                 │                    │<br>                 │                    ▼<br>                 │               OS facilities<br>                 │<br>                 └───────────────┬────────────────┘<br>                                 │<br>                         callbacks ready<br>                                 │<br>                                 ▼<br>                                V8<br>                                 │<br>                                 ▼<br>                         JavaScript executes</pre><p>The important relationships are:</p><h3>V8</h3><p><strong>Executes JavaScript.</strong></p><h3>Node.js APIs</h3><p><strong>Expose capabilities such as files, networking, processes, crypto, etc. to JavaScript.</strong></p><h3>Bindings/native layer</h3><p><strong>Bridge JavaScript-facing Node functionality with native implementations.</strong></p><h3>libuv</h3><p><strong>Provides much of Node’s asynchronous I/O infrastructure.</strong></p><h3>Event loop</h3><p><strong>Coordinates when ready asynchronous work should result in JavaScript callbacks being executed.</strong></p><h3>Worker pool</h3><p><strong>Provides background threads for certain operations that cannot conveniently be performed using non-blocking OS mechanisms.</strong></p><h3>OS</h3><p><strong>Provides the underlying networking, filesystem, process, and other system facilities.</strong></p><h3>17. The One Sentence That Explains Node.js</h3><p>If you understand the entire article, you should be able to explain Node.js like this:</p><blockquote><strong><em>Node.js embeds V8 to execute JavaScript and provides Node-specific APIs whose implementations can interact with native components such as libuv, the operating system, and OpenSSL. JavaScript itself executes on one main thread, while asynchronous operations can be handled by OS facilities or background workers, allowing the event loop to keep the JavaScript thread available for other work.</em></strong></blockquote><p>That’s much more accurate than:</p><blockquote><em>“Node.js is single-threaded.”</em></blockquote><h3>18. Where We Go Next</h3><p>We’ve now established the layers:</p><pre>JavaScript<br>    ↓<br>V8<br>    ↓<br>Node.js APIs<br>    ↓<br>Native layer / bindings<br>    ↓<br>libuv<br>    ↓<br>OS / worker pool<br>    ↓<br>completion<br>    ↓<br>event loop<br>    ↓<br>V8<br>    ↓<br>callback</pre><p>But we’ve intentionally treated the <strong>event loop as a black box</strong>.</p><p>That’s the next thing we need to open.</p><p>In Part 2, we’ll go inside the event loop itself:</p><ul><li>What actually happens in each phase?</li><li>Where do timers fit?</li><li>What does setTimeout(fn, 0) really mean?</li><li>Why can setImmediate() execute before a timer?</li><li>What is the poll phase?</li><li>Where do I/O callbacks run?</li><li>What exactly does process.nextTick() do?</li><li>Why can nextTick() starve the event loop?</li></ul><p>Because once you understand those mechanisms, the phrase <strong>“Node.js is single-threaded but concurrent”</strong> stops being a slogan and becomes something you can actually reason about.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97b2fb3fbb51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Partition vs Shard vs Partition Key: Understanding Data Distribution]]></title>
            <link>https://medium.com/@rajatraghav7797/partition-vs-shard-vs-partition-key-understanding-data-distribution-7c5c9e1242a1?source=rss-d50c9c063b6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c5c9e1242a1</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Rajat Kumar]]></dc:creator>
            <pubDate>Wed, 19 Aug 2026 06:17:30 GMT</pubDate>
            <atom:updated>2026-08-19T06:17:30.657Z</atom:updated>
            <content:encoded><![CDATA[<p>When learning databases and distributed systems, three terms appear again and again:</p><ul><li><strong>Partition</strong></li><li><strong>Partition Key</strong></li><li><strong>Shard</strong></li></ul><p>They sound similar, and different databases sometimes use them differently. This makes the topic surprisingly confusing. Let’s build the concepts from the ground up using PostgreSQL and Cassandra.</p><h3>1. Start With a Table</h3><p>Suppose we have a PostgreSQL table called users:</p><pre>CREATE TABLE users (<br>    user_id BIGINT,<br>    name TEXT,<br>    email TEXT<br>);</pre><p>Logically, we see one table:</p><pre>users<br> ├── user 1<br> ├── user 2<br> ├── user 3<br> ├── ...<br> └── user 1,000,000</pre><p>As the table grows, managing and querying all of this data can become expensive.</p><p>One solution is <strong>partitioning</strong>.</p><h3>2. What Is a Partition?</h3><p>A partition is a subdivision of a larger dataset.</p><p>We could partition the users table based on user_id:</p><pre>                   users<br>                      │<br>          ┌───────────┼───────────┐<br>          ↓           ↓           ↓<br>       users_1     users_2     users_3<br>       1–999999    1M–1.99M    2M–2.99M</pre><p>Conceptually, we still have one logical users table, but PostgreSQL stores its data in multiple partitions.</p><p>For example:</p><pre>CREATE TABLE users (<br>    user_id BIGINT,<br>    name TEXT,<br>    email TEXT<br>) PARTITION BY RANGE (user_id);</pre><p>Then we define the partitions:</p><pre>CREATE TABLE users_1<br>    PARTITION OF users<br>    FOR VALUES FROM (1) TO (1000000);<br><br>CREATE TABLE users_2<br>    PARTITION OF users<br>    FOR VALUES FROM (1000000) TO (2000000);</pre><p>So a partition is essentially a <strong>piece of the larger table</strong>.</p><h3>3. What Is a Partition Key?</h3><p>Now we need a way to determine which partition should contain a particular row. That’s where the <strong>partition key</strong> comes in.</p><p>In our example:</p><pre>partition key = user_id</pre><p>Suppose we insert:</p><pre>INSERT INTO users<br>VALUES (1500000, &#39;Rajat&#39;, &#39;rajat@example.com&#39;);</pre><p>PostgreSQL looks at:</p><pre>user_id = 1,500,000</pre><p>and determines:</p><pre>1,000,000 ≤ 1,500,000 &lt; 2,000,000<br>             ↓<br>          users_2</pre><p>The application doesn’t need to decide this. We don’t write:</p><pre>if userId &lt; 1M:<br>    insert into users_1<br>else:<br>    insert into users_2</pre><p>Instead, we simply write:</p><pre>INSERT INTO users ...</pre><p>and PostgreSQL routes the row to the appropriate partition. So:</p><blockquote><strong><em>Partition key = the value used to determine which partition should contain the data.</em></strong></blockquote><h3>4. Who Manages the Partitions?</h3><p>This is an important question. The <strong>developer/database administrator defines the partitioning strategy</strong>.</p><p>For example, we decide:</p><pre>Table       → users<br>Partitioning → RANGE<br>Partition key → user_id<br>Boundaries   → 0–1M, 1M–2M, etc.</pre><p>But once those partitions are defined, <strong>PostgreSQL manages the runtime behavior</strong>.</p><p>PostgreSQL handles things such as:</p><ul><li>Routing inserts to the correct partition</li><li>Querying the appropriate partitions</li><li>Partition pruning</li><li>Maintaining the partition hierarchy</li></ul><p>For example:</p><pre>SELECT *<br>FROM users<br>WHERE user_id = 1500000;</pre><p>PostgreSQL can determine that user_id = 1500000 can only exist in users_2. It doesn’t need to scan every partition. This optimization is called <strong>partition pruning</strong>.</p><h3>5. Is a Partition the Same as a Shard?</h3><p>Not exactly. This is one of the most important distinctions in distributed systems. Suppose PostgreSQL has:</p><pre>               PostgreSQL Server<br>                       │<br>                    users<br>                       │<br>          ┌────────────┼────────────┐<br>          ↓            ↓            ↓<br>       users_1      users_2      users_3</pre><p>The partitions are subdivisions of the table, but they can all be managed by the <strong>same PostgreSQL database/server</strong>. That’s table partitioning.</p><p>Now consider:</p><pre>                  Application<br>                         │<br>              ┌──────────┼──────────┐<br>              ↓          ↓          ↓<br>          PostgreSQL PostgreSQL PostgreSQL<br>           Server 1   Server 2   Server 3<br>              │          │          │<br>           users_1     users_2     users_3</pre><p>Now the data is distributed across separate database servers. This is typically called <strong>sharding</strong>. So the simplified distinction is:</p><blockquote><strong><em>Partitioning divides data. Sharding distributes those divisions across independent nodes.</em></strong></blockquote><p>A shard is therefore often thought of as a <strong>piece of the overall dataset living on a separate machine/database instance</strong>.</p><h3>6. Why Do We Need Sharding?</h3><p>Imagine our users table has:</p><pre>10 billion rows</pre><p>One PostgreSQL server may eventually become a bottleneck. We could distribute the data:</p><pre>                   Application<br>                         │<br>                    user_id<br>                         │<br>              ┌──────────┼──────────┐<br>              ↓          ↓          ↓<br>            Shard 1    Shard 2    Shard 3<br>            DB-1       DB-2       DB-3</pre><p>Now each database server handles only a portion of the total data and traffic. This gives us <strong>horizontal scaling</strong>. Instead of buying a single increasingly powerful machine, we add more machines.</p><h3>7. Now Cassandra Changes the Picture</h3><p>This is where terminology becomes confusing. PostgreSQL and Cassandra both use the word <strong>partition</strong>, but partitioning plays a different role. In PostgreSQL, partitioning is an optional feature you can use to divide a table. In Cassandra, partitioning is fundamental to how data is distributed across the cluster. Suppose we have:</p><pre>CREATE TABLE orders (<br>    user_id UUID,<br>    order_id UUID,<br>    amount DECIMAL,<br>    PRIMARY KEY ((user_id), order_id)<br>);</pre><p>Notice:</p><pre>PRIMARY KEY ((user_id), order_id)<br>            ↑<br>       partition key</pre><p>Here, user_id is the Cassandra partition key. Suppose we have:</p><pre>user_id = 101</pre><p>and several orders:</p><pre>user_id = 101, order_id = 1<br>user_id = 101, order_id = 2<br>user_id = 101, order_id = 3</pre><p>These rows belong to the same Cassandra partition:</p><pre>Partition: user_id = 101<br> ├── order 1<br> ├── order 2<br> └── order 3</pre><p>Another user has another partition:</p><pre>Partition: user_id = 102<br> ├── order 4<br> └── order 5</pre><h3>8. How Does Cassandra Decide Where the Partition Goes?</h3><p>Cassandra takes the partition key and hashes it. Conceptually:</p><pre>user_id<br>   ↓<br>hash(user_id)<br>   ↓<br>token<br>   ↓<br>Cassandra node</pre><p>For example:</p><pre>user_id = 101<br>      ↓<br>    hash<br>      ↓<br>   token X<br>      ↓<br>   Node 2</pre><p>Another user might map somewhere else:</p><pre>user_id = 102<br>      ↓<br>    hash<br>      ↓<br>   token Y<br>      ↓<br>   Node 3</pre><p>So Cassandra automatically distributes partitions across the cluster. The application doesn’t say:</p><pre>&quot;Put user 101 on Node 2.&quot;</pre><p>It simply writes the data. Cassandra’s partitioning mechanism determines where that data belongs.</p><h3>9. Why Cassandra’s Partition Key Is So Important</h3><p>In Cassandra, choosing a partition key is a major data-modeling decision.</p><p>A good partition key should generally:</p><ul><li>Distribute data evenly</li><li>Distribute traffic evenly</li><li>Avoid extremely large partitions</li><li>Match important query patterns</li></ul><p>For example, if we choose:</p><pre>user_id</pre><p>as the partition key:</p><pre>user 101 → partition A<br>user 102 → partition B<br>user 103 → partition C</pre><p>But if we choose:</p><pre>country</pre><p>as the partition key:</p><pre>India → millions of rows<br>USA   → millions of rows<br>UK    → fewer rows</pre><p>We might create very large or heavily accessed partitions. This can lead to <strong>hot partitions</strong> and poor performance.</p><h3>10. PostgreSQL vs Cassandra</h3><p>Now we can compare them directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RT_s11DRR3_IX-JKxNysFw.png" /></figure><p>The important thing is that <strong>the same word doesn’t imply exactly the same implementation</strong>.</p><h3>11. The Mental Model</h3><p>A useful mental model is:</p><pre>                  DATA<br>                   │<br>            ┌──────┴──────┐<br>            │             │<br>      Partitioning     Sharding<br>            │             │<br>      Divide data     Distribute data<br>            │             │<br>            ↓             ↓<br>      Partitions       Shards</pre><p>And the key used to make the decision is:</p><pre>                Partition Key<br>                       │<br>                       ↓<br>                Where does this<br>                  data belong?</pre><p>But remember that different systems implement this differently.</p><h3>12. The Most Important Takeaway</h3><p>Don’t memorize:</p><blockquote><em>“A partition is always a table.”</em></blockquote><p>or:</p><blockquote><em>“A partition is always a machine.”</em></blockquote><p>Neither is universally correct. Instead remember:</p><h3>Partition</h3><p>A <strong>logical/physical subdivision of data</strong>.</p><h3>Partition key</h3><p>The <strong>value used to determine how data is grouped or where it belongs</strong>.</p><h3>Shard</h3><p>A <strong>portion of a larger dataset distributed to a separate node/database instance</strong>, usually for horizontal scaling.</p><p>And finally:</p><blockquote><strong><em>PostgreSQL table partitioning and Cassandra partitioning use the same broad idea — divide data into smaller pieces — but they solve different problems and operate at different levels of the system.</em></strong></blockquote><p>This distinction becomes especially important when you move from traditional relational databases to distributed systems such as <strong>Cassandra, DynamoDB, Kafka, and distributed SQL databases</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c5c9e1242a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Concurrency & Async: The Complete Picture]]></title>
            <link>https://medium.com/@rajatraghav7797/java-concurrency-async-the-complete-picture-2875d4692a1a?source=rss-d50c9c063b6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2875d4692a1a</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <dc:creator><![CDATA[Rajat Kumar]]></dc:creator>
            <pubDate>Fri, 14 Aug 2026 17:32:45 GMT</pubDate>
            <atom:updated>2026-08-14T17:32:45.656Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 7 — Virtual Threads: How the JVM Reinvented Threading From the Ground Up</h3><p><em>Part of the series: Java Concurrency &amp; Async — The Complete Picture</em></p><h3>A Story About a Waiter</h3><p>Imagine a restaurant with 200 tables. The owner hires exactly 8 waiters.</p><p>Most restaurants at this point would be in chaos — 8 people can’t possibly serve 200 tables simultaneously. But this restaurant has a rule: a waiter never stands next to a table waiting. The moment a waiter takes an order and sends it to the kitchen, they walk to another table immediately. When the kitchen rings the bell, any available waiter picks up the food and delivers it.</p><p>The waiters are always moving. Never standing still waiting for the kitchen.</p><p>This is how modern async programming works — CompletableFuture, reactive frameworks. The “waiters” are your threads. “Standing still waiting for the kitchen” is blocking I/O — a database query, an HTTP call. The insight: don’t waste a thread blocking. Give it other work while it waits.</p><p>It works. It’s efficient. There’s just one problem.</p><p><strong>It’s incredibly hard to program.</strong></p><p>Instead of writing code the natural way — call this, wait for result, call that — you’re writing chains of callbacks. You’re thinking about which thread pool each step runs on. You’re managing CompletableFuture&lt;CompletableFuture&lt;T&gt;&gt;. Stack traces become meaningless — the call that caused the problem is three async stages removed from where the exception lands.</p><p>Engineers started saying “async is contagious” — once one method is async, everything that calls it has to be async too. Systems built this way are correct but hard to read, hard to debug, hard to onboard.</p><p>There had to be a better way. To understand what Java 21 built, we first need to understand why threads were expensive in the first place.</p><h3>Part 1: What a Thread Actually Is at the OS Level</h3><p>When you write new Thread(() -&gt; doWork()).start() in Java, here is exactly what physically happens.</p><p>The JVM calls pthread_create() on Linux — a <strong>kernel system call</strong> that crosses the user-space/kernel-space boundary and asks the operating system to create a new <strong>kernel thread</strong>.</p><p>The OS does:</p><ul><li>Allocates a <strong>kernel stack</strong> (~8KB) for the thread</li><li>Allocates the <strong>Java stack</strong> (default 512KB–1MB, configurable via -Xss)</li><li>Creates a <strong>task struct</strong> — the data structure the OS scheduler uses to track this thread</li><li>Registers the thread with the <strong>CPU scheduler</strong></li></ul><p>From this point, your Java thread is a first-class OS citizen. The OS scheduler decides when it runs, which CPU core, and for how long. The JVM has no say — it’s entirely the OS’s responsibility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vfZ3GsgzkF05V6K-iOxTfQ.png" /></figure><p><em>Figure: Every Java platform thread maps to one OS kernel thread. The OS scheduler manages all threads. Each thread gets its own dedicated stack allocation regardless of whether it’s doing work or sitting idle.</em></p><p><strong>The cost breakdown:</strong></p><pre>Creating a platform thread:<br>  System call overhead:     1-2 microseconds (crossing user/kernel boundary)<br>  Kernel thread setup:      10-50 microseconds<br>  Stack allocation:         512KB–1MB of memory, always<br>  Scheduler registration:   O(log n) insertion into the kernel run queue<br><br>Context switch between threads:<br>  Save CPU registers of outgoing thread:    ~100 nanoseconds<br>  Restore CPU registers of incoming thread: ~100 nanoseconds<br>  CPU cache pollution:                      hundreds of cache misses<br>  Total cost:                               1-10 microseconds per switch</pre><p>This is why you cannot have 100,000 platform threads. It’s not a JVM limitation — it’s a kernel limitation. Linux starts degrading at ~10,000–50,000 threads because the scheduler’s run queue becomes too large to manage efficiently.</p><h3>Part 2: The I/O Mismatch — Paying for Threads That Do Nothing</h3><p>A platform thread has two states from the OS’s perspective:</p><p><strong>RUNNING</strong> — executing instructions on a CPU core. <strong>BLOCKED</strong> — waiting for something. The OS removes it from the run queue. The CPU core is freed.</p><p>When a Java thread does:</p><pre>ResultSet rs = statement.executeQuery(&quot;SELECT * FROM orders WHERE id = 42&quot;);</pre><p>What physically happens:</p><ol><li>JDBC driver sends a TCP packet to Postgres</li><li>Thread calls socket.read() to wait for the response</li><li>OS immediately blocks the thread — goes to BLOCKED state</li><li>CPU core is freed for other threads</li><li>5–50ms later, Postgres responds</li><li>OS wakes the thread, puts it back in the run queue</li><li>Scheduler gives it a CPU core, execution resumes</li></ol><p>The thread is consuming its 1MB of stack memory <strong>the entire time it’s blocked</strong>. Doing absolutely nothing — just sitting in the OS’s blocked thread list — it still occupies memory and a kernel task struct.</p><p>If you have 10,000 concurrent requests each blocked waiting for Postgres:</p><ul><li>10,000 platform threads = <strong>10GB of stack memory</strong></li><li>10,000 kernel task structs the scheduler must manage</li><li>When Postgres responds to all simultaneously: 10,000 threads wake up at once — thundering herd</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q50DiSgCMiSfv3u5zk74EA.png" /></figure><p><em>Figure: A thread blocked on I/O. The CPU core is freed, but the thread’s 1MB stack remains allocated for the entire wait duration. At 10,000 concurrent requests, this becomes 10GB of memory doing nothing.</em></p><p><strong>This is the fundamental mismatch:</strong> the OS thread is a unit of CPU scheduling. But blocking I/O doesn’t need CPU — it just needs to wait. You’re paying the full cost of an OS thread to do nothing but wait.</p><p>This mismatch is exactly why async programming was invented. CompletableFuture, reactive streams, async/await — they all exist to work around this one problem. But what if you could block without paying the platform thread cost?</p><h3>Part 3: The Insight — Separate Execution Context from OS Thread</h3><p>Virtual threads solve the mismatch by separating two concepts that platform threads conflate:</p><p><strong>The execution context</strong> — the call stack, local variables, the program counter (which instruction to execute next). The “position” in the code.</p><p><strong>The OS thread</strong> — the thing the CPU scheduler actually runs.</p><p>In a platform thread, these are the same object. The stack lives in the OS thread’s memory region. You can’t have one without the other.</p><p>In a virtual thread, they are <strong>separated</strong>:</p><ul><li>The execution context is captured in a heap object called a <strong>continuation</strong></li><li>The OS thread — called a <strong>carrier thread</strong> — is just the vehicle it temporarily runs on</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nW9GuF37xXwKUDQiWFtNlA.png" /></figure><p><em>Figure: A virtual thread is a continuation object on the heap (storing call stack + program counter) mounted temporarily onto a carrier thread (OS thread) to execute. The two can be separated at any blocking point.</em></p><p>The JVM maintains a small pool of <strong>carrier threads</strong> — typically N_cpu in count. These are normal OS threads. They&#39;re what actually runs on the CPU. Everything else is virtual threads scheduled on top of them.</p><h3>Part 4: Mount, Execute, Unmount — The Lifecycle</h3><p>Here is exactly what happens when a virtual thread runs:</p><p><strong>Mounting:</strong></p><ol><li>JVM picks an available carrier thread</li><li>The continuation’s saved stack frames are <strong>copied from the heap onto the carrier thread’s OS stack</strong></li><li>The saved program counter is restored into the CPU instruction pointer</li><li>Execution begins — code runs normally on the carrier thread</li></ol><p><strong>Hitting a blocking operation:</strong></p><ol><li>Code calls socket.read() (or any I/O, lock wait, sleep)</li><li>JVM detects: blocking operation on a virtual thread</li><li>JVM <strong>copies the entire call stack back from the carrier thread’s OS stack into the continuation object on the heap</strong></li><li>Carrier thread’s OS stack is now empty — free for another virtual thread</li><li>JVM registers the socket with the OS using non-blocking I/O (epoll on Linux)</li><li>Carrier thread immediately picks up the next virtual thread and mounts it</li></ol><p><strong>Resuming:</strong></p><ol><li>OS signals data is available (epoll event fires)</li><li>JVM’s poller thread detects the event</li><li>JVM marks the continuation as runnable</li><li>Next available carrier thread mounts it — copies stack frames from heap back to OS stack</li><li>Execution resumes exactly where it left off: same variables, same stack depth, same program counter</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HdkbTTU-mG53GSoGk_WGPg.png" /></figure><p><em>Figure: On blocking: stack copied from OS stack → heap continuation. On resume: heap continuation → OS stack of any available carrier. The carrier thread is free between mount and unmount — it serves other virtual threads.</em></p><p>From your code: socket.read() blocked, then returned data. Normal sequential execution. From the OS: the carrier thread never blocked. It kept running other virtual threads the entire time.</p><h3>Part 5: The Stack Copy — What Unmounting Physically Means</h3><p>When a platform thread executes, its call stack lives in memory the OS allocated specifically for that thread. The stack pointer register (RSP on x86–64) points into this region. Local variables are at offsets from the stack pointer. The whole thing is inseparable from that OS thread’s memory.</p><p>When a virtual thread unmounts, the JVM does something remarkable:</p><p><strong>It copies the entire call stack from the carrier thread’s OS stack into a heap-allocated Java object — the continuation.</strong></p><p>Every stack frame. Every local variable on every frame. The saved return address for each frame. All of it moves from native OS memory onto the Java heap. The carrier thread’s OS stack is now empty.</p><p>When the virtual thread remounts — possibly onto a different carrier thread, possibly on a different CPU core:</p><p><strong>The JVM copies the continuation’s stack frames back onto the carrier thread’s OS stack.</strong></p><p>The instruction pointer is restored. Execution continues exactly where it left off.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cZtbjDZo8zraQ4zeL3yvvA.png" /></figure><p><em>Figure: Left: mounted virtual thread — stack frames live on carrier’s OS stack. Right: unmounted — same frames in continuation object on JVM heap. The carrier’s stack is empty and free. On remount, frames copy back.</em></p><p><strong>The cost of this operation:</strong></p><pre>Virtual thread mount/unmount:<br>  Operation:       pure JVM userspace — zero kernel involvement<br>  System call:     none<br>  Stack to copy:   proportional to current call stack depth<br>  Typical cost:    100–500 nanoseconds<br><br>Platform thread context switch:<br>  Operation:       OS scheduler involvement<br>  System call:     yes - crosses kernel/user boundary<br>  Cost:            1–10 microseconds</pre><p>10–100x cheaper than platform thread context switching. And no kernel involvement whatsoever.</p><h3>Part 6: How Much Does a Virtual Thread Actually Cost?</h3><pre>Platform thread — always:<br>  Java Thread object:     ~400 bytes<br>  OS stack:               512KB–1MB  ← always allocated, even when blocked<br>  Kernel task struct:     ~few KB in kernel memory<br>  Total:                  512KB–1MB per thread, at all times<br><br>Virtual thread - created, not yet started:<br>  Java Thread object:     ~200 bytes<br>  Continuation:           few hundred bytes<br>  Total:                  &lt; 1KB<br><br><br>Virtual thread - unmounted, blocked on I/O:<br>  Continuation with stack: 2KB–20KB (typical web request handler depth)<br>  OS stack allocation:     zero - shares carrier thread&#39;s stack when mounted<br>  Total:                   2KB–20KB in heap<br><br><br>Virtual thread - mounted, executing:<br>  Uses carrier thread&#39;s OS stack temporarily<br>  Continuation on heap:   still there, frames currently on OS stack</pre><p>This is why you can have millions of virtual threads. A million virtual threads blocked on I/O might consume 2–20GB of heap for their continuations. Compare to a million platform threads at 1MB each: <strong>1 terabyte</strong>. Not comparable.</p><h3>Part 7: The Blocking I/O Reimplementation</h3><p>The piece that makes everything work transparently: the JVM reimplemented all standard Java blocking I/O to be virtual-thread-aware.</p><p>When a virtual thread calls socket.read():</p><pre>JVM checks: are we on a virtual thread?<br>  NO  → traditional blocking path (OS blocks the platform thread)<br>  YES → virtual-thread-aware path:<br>    1. Register socket with epoll/kqueue (OS non-blocking I/O mechanism)<br>    2. Unmount this virtual thread (save continuation to heap)<br>    3. Return carrier thread to pool — immediately picks up next virtual thread<br>    4. [time passes — Postgres sends a response]<br>    5. OS signals the epoll event fires<br>    6. JVM poller thread detects it<br>    7. Mark continuation as runnable<br>    8. Carrier thread mounts it, restores stack<br>    9. socket.read() returns with data — as if nothing unusual happened</pre><p>The reimplementation is inside java.net.Socket, java.io.InputStream, java.nio, and the JDBC socket layer. Your code calls the same APIs. The behavior is identical from the outside. The mechanism underneath is completely different.</p><p>This is why virtual threads require zero code changes. Same API. Same semantics. Completely different implementation.</p><h3>Part 8: The Code</h3><pre>// One virtual thread<br>Thread vt = Thread.ofVirtual().start(() -&gt; handleRequest(request));<br><br>// Virtual thread per task - the production pattern<br>try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {<br>    for (int i = 0; i &lt; 100_000; i++) {<br>        executor.submit(() -&gt; handleRequest());<br>    }<br>}<br>// 100,000 tasks, ~N_cpu carrier threads, far less than 100,000 × 1MB memory</pre><p>The code inside each task:</p><pre>// Virtual thread handler — reads like synchronous code from 1998<br>// Each blocking call unmounts the virtual thread silently<br>public Response handleRequest(Request req) {<br>    User user = database.findUser(req.getUserId());       // unmounts → remounts<br>    Recommendations recs = recService.get(user.getId());  // unmounts → remounts<br>    database.saveAuditLog(user, recs);                    // unmounts → remounts<br>    return buildResponse(user, recs);<br>}</pre><p><strong>Before/after — the full async tax:</strong></p><pre>// BEFORE — CompletableFuture, correct but complex<br>public CompletableFuture&lt;Response&gt; handleRequest(Request req) {<br>    return CompletableFuture<br>        .supplyAsync(() -&gt; database.findUser(req.getUserId()), dbPool)<br>        .thenCompose(user -&gt;<br>            CompletableFuture<br>                .supplyAsync(() -&gt; recService.get(user.getId()), httpPool)<br>                .thenApply(recs -&gt; Pair.of(user, recs))<br>        )<br>        .thenCompose(pair -&gt;<br>            CompletableFuture<br>                .runAsync(() -&gt; database.saveAuditLog(<br>                    pair.getLeft(), pair.getRight()), dbPool)<br>                .thenApply(v -&gt; pair)<br>        )<br>        .thenApply(pair -&gt; buildResponse(pair.getLeft(), pair.getRight()))<br>        .exceptionally(ex -&gt; {<br>            log.error(&quot;Failed&quot;, ex);<br>            return Response.error();<br>        });<br>}<br><br>// AFTER - virtual threads, same concurrency, sequential clarity<br>public Response handleRequest(Request req) {<br>    try {<br>        User user = database.findUser(req.getUserId());<br>        Recommendations recs = recService.get(user.getId());<br>        database.saveAuditLog(user, recs);<br>        return buildResponse(user, recs);<br>    } catch (Exception ex) {<br>        log.error(&quot;Failed&quot;, ex);<br>        return Response.error();<br>    }<br>}</pre><p>Same throughput. Same concurrency. Readable code. Meaningful stack traces. Normal try/catch. Everything you know about writing Java works.</p><h3>Part 9: Spring Boot — One Line</h3><pre># application.yml<br>spring:<br>  threads:<br>    virtual:<br>      enabled: true</pre><p>Every incoming HTTP request now runs on a virtual thread. Tomcat’s thread pool tuning — a critical bottleneck with platform threads — becomes largely irrelevant. The JVM creates a virtual thread per request, and the small carrier thread pool handles scheduling automatically.</p><h3>Part 10: Pinning — The One Catch</h3><p>A virtual thread is <strong>pinned</strong> to its carrier thread when it blocks inside:</p><ul><li>A synchronized block or method</li><li>A native method call</li></ul><p>When pinned, the virtual thread cannot unmount. The carrier thread blocks — exactly like a platform thread. The benefit disappears.</p><p><strong>Why </strong><strong>synchronized causes pinning:</strong></p><p>The monitor lock (Java’s intrinsic lock) is tied to the <strong>carrier thread’s identity</strong> at the JVM implementation level — not the virtual thread. If the JVM stored “carrier thread X holds lock A” and then unmounted the virtual thread, carrier thread X would move on to other work while still appearing to hold lock A. Inconsistent state. Disaster.</p><p>The JVM’s only safe option: keep the virtual thread mounted (pinned) for the entire duration of the synchronized block.</p><pre>// PINNING — carrier blocked during DB query<br>public synchronized void updateWithLock() {<br>    database.query(sql);  // carrier thread stuck here<br>}<br><br>// NO PINNING - ReentrantLock stores owner in heap, not carrier thread<br>private final ReentrantLock lock = new ReentrantLock();<br><br>public void updateWithLock() {<br>    lock.lock();<br>    try {<br>        database.query(sql);  // virtual thread unmounts here - carrier free<br>    } finally {<br>        lock.unlock();<br>    }<br>}</pre><p>ReentrantLock uses AbstractQueuedSynchronizer — a pure Java data structure that tracks which <strong>virtual thread</strong> holds the lock, stored on the heap. Unmounting is safe because the lock ownership survives the unmount.</p><p><strong>Detecting pinning:</strong></p><pre>-Djdk.tracePinnedThreads=full</pre><p>Logs a stack trace every time a virtual thread pins. Run during load testing. If your own code appears, replace synchronized with ReentrantLock in I/O paths. Most modern libraries (JDBC, Spring, Hibernate) are already updated.</p><h3>Part 11: ThreadLocal and ScopedValue</h3><p>ThreadLocal works with virtual threads but becomes a memory problem at scale.</p><p>With a platform thread pool of 200 threads: 200 ThreadLocal slots — bounded. With 100,000 active virtual threads: 100,000 ThreadLocal slots — potentially 100,000 large objects in memory.</p><p>Java 21 introduces <strong>ScopedValue</strong> as the replacement:</p><pre>// Old: ThreadLocal — must manually clean up, leaks if forgotten<br>private static final ThreadLocal&lt;User&gt; CURRENT_USER = new ThreadLocal&lt;&gt;();<br>CURRENT_USER.set(authenticatedUser);<br>// ... do work ...<br>CURRENT_USER.remove();  // forget this → memory leak<br><br>// New: ScopedValue - automatically cleaned up, immutable, no leaks<br>private static final ScopedValue&lt;User&gt; CURRENT_USER = ScopedValue.newInstance();<br>ScopedValue.where(CURRENT_USER, authenticatedUser)<br>           .run(() -&gt; processRequest());  // available anywhere in the call tree<br>// Scope closes → value gone automatically</pre><p>ScopedValue is immutable within its scope (no accidental sharing between virtual threads), automatically cleaned up when the scope closes, and inherited by nested scopes. For new code on Java 21+, prefer it over ThreadLocal.</p><h3>Part 12: Structured Concurrency</h3><p>Virtual threads make concurrent code easy to write. Structured concurrency makes it easy to reason about.</p><p><strong>The problem with unstructured concurrency:</strong></p><pre>CompletableFuture&lt;Profile&gt; pF = CompletableFuture.supplyAsync(...);<br>CompletableFuture&lt;Activity&gt; aF = CompletableFuture.supplyAsync(...);<br>CompletableFuture&lt;Integer&gt; nF = CompletableFuture.supplyAsync(...);<br><br>CompletableFuture.allOf(pF, aF, nF).join();<br>// pF fails → aF and nF keep running (wasted work)<br>// Request cancelled → nothing stops the three subtasks<br>// Two fail → only one exception propagates (other silently lost)</pre><p><strong>Structured concurrency:</strong></p><pre>public Dashboard getDashboard(Long userId) throws Exception {<br>    try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {<br>        var profile  = scope.fork(() -&gt; profileService.get(userId));<br>        var activity = scope.fork(() -&gt; activityService.get(userId));<br>        var notifs   = scope.fork(() -&gt; notifService.count(userId));<br>        scope.join()           // wait for all three<br>             .throwIfFailed(); // any failed → others cancelled → exception thrown<br>        return new Dashboard(profile.get(), activity.get(), notifs.get());<br>    }<br>    // scope closes → all forked tasks guaranteed done or cancelled<br>}</pre><p><strong>The core invariant:</strong> tasks cannot outlive their scope. When the try block exits — normally or via exception — all forked tasks are done or cancelled. No work escapes. No background threads outliving the caller.</p><p><strong>Two policies:</strong></p><pre>// ShutdownOnFailure — all must succeed<br>try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {<br>    var t1 = scope.fork(() -&gt; fetchA());<br>    var t2 = scope.fork(() -&gt; fetchB());<br>    scope.join().throwIfFailed();<br>    return combine(t1.get(), t2.get());<br>}<br><br>// ShutdownOnSuccess - first result wins<br>try (var scope = new StructuredTaskScope.ShutdownOnSuccess&lt;String&gt;()) {<br>    scope.fork(() -&gt; fetchFromPrimary());<br>    scope.fork(() -&gt; fetchFromReplica());<br>    scope.fork(() -&gt; fetchFromCache());<br>    scope.join();<br>    return scope.result();  // fastest successful result<br>}</pre><p>Virtual threads + structured concurrency together:</p><pre>public OrderSummary getOrderSummary(Long orderId) throws Exception {<br>    try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {<br>        // Each fork = one virtual thread, sequential code inside, parallel execution<br>        var order    = scope.fork(() -&gt; orderService.find(orderId));<br>        var customer = scope.fork(() -&gt; customerService.find(orderId));<br>        var items    = scope.fork(() -&gt; inventoryService.listItems(orderId));<br>        var history  = scope.fork(() -&gt; auditService.getHistory(orderId));<br><br>        scope.join().throwIfFailed();<br>        return OrderSummary.builder()<br>            .order(order.get())<br>            .customer(customer.get())<br>            .items(items.get())<br>            .history(history.get())<br>            .build();<br>    }<br>}</pre><p>Four services called in parallel. Sequential code inside each. Scope guarantees cleanup. No thread pools to configure. No CompletableFuture. This is concurrent Java in 2025.</p><h3>Part 13: The Complete Mental Model</h3><pre>Platform thread:<br>  Java Thread object<br>      ↓ 1:1 mapping<br>  OS kernel thread<br>      → dedicated OS stack (512KB–1MB, always allocated)<br>      → kernel task struct<br>      → CPU scheduler tracking<br>  Blocked: OS thread idle, memory consumed, scheduler tracking continues<br><br>Virtual thread:<br>  Java Thread object (~200 bytes)<br>      ↓ contains<br>  Continuation (heap: 2KB–20KB typical)<br>      ↓ scheduled by JVM onto<br>  Carrier thread (platform thread, 1 per CPU core)<br>      → shared OS stack (used only while mounted)<br>      → kernel task struct (shared across all virtual threads)<br>  Blocked: continuation saved to heap, carrier freed, OS unaware<br></pre><p>The OS sees N carrier threads, always busy. The JVM sees millions of virtual threads, most parked, a few running. The programmer sees simple sequential code. Everyone gets what they want.</p><h3>What Changes, What Doesn’t</h3><p><strong>Changes:</strong></p><ul><li>Thread-per-request is no longer expensive</li><li>Thread pool sizing for I/O-bound work is largely irrelevant</li><li>CompletableFuture often unnecessary for &quot;don&#39;t block&quot; — just block on a virtual thread</li><li>Heavy synchronized in I/O paths → replace with ReentrantLock</li><li>ThreadLocal at scale → prefer ScopedValue</li></ul><p><strong>Doesn’t change:</strong></p><ul><li>CPU-bound work still needs bounded parallelism — use parallel streams (Part 6)</li><li>Shared mutable state is still dangerous — Parts 2 and 3 still apply</li><li>The JVM memory model still applies</li><li>synchronized still causes pinning — a current limitation, not permanent</li><li>Slow algorithms don’t become fast — virtual threads help concurrency, not computation</li></ul><h3>Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eOTJ1iXFxRuyNXyFlMExmQ.png" /></figure><p>Virtual threads are the most significant change to Java concurrency since Java 5. They don’t invalidate everything in this series — locks, atomicity, thread pools, CompletableFuture all still have their roles. But for the dominant production case — services handling concurrent requests, each waiting on databases and external APIs — virtual threads let you write the sequential code you always wanted to write, at the scale you previously needed complex async plumbing to achieve.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2875d4692a1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Concurrency & Async: The Complete Picture]]></title>
            <link>https://medium.com/@rajatraghav7797/java-concurrency-async-the-complete-picture-7f34d44ebc80?source=rss-d50c9c063b6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f34d44ebc80</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[concurrent-programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Rajat Kumar]]></dc:creator>
            <pubDate>Sun, 09 Aug 2026 19:04:33 GMT</pubDate>
            <atom:updated>2026-08-09T19:04:33.927Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 6 — Fork/Join &amp; Parallel Streams: When the CPU Is the Bottleneck</h3><p><em>Part of the series: Java Concurrency &amp; Async — The Complete Picture</em></p><h3>A Problem That Looks Simple</h3><p>It’s Monday morning. Your manager drops a request on your desk.</p><p>“We have 10 million shipment records. End of quarter. Finance needs the total revenue across all of them. By noon.”</p><p>You open your laptop, write the obvious solution:</p><pre>double total = shipments.stream()<br>    .mapToDouble(Shipment::getAmount)<br>    .sum();</pre><p>You run it. It takes 47 seconds.</p><p>Your manager is not impressed.</p><p>The data is already in memory — a giant List&lt;Shipment&gt;. No database, no network, no I/O. Just math. Just the CPU grinding through 10 million multiplications and additions, one at a time, on a single core, while the other seven cores on your machine sit completely idle.</p><p>This is the problem Fork/Join was built to solve. Not “how do we stop waiting for external systems” — CompletableFuture handles that. But “how do we use all the CPU we already have” when the work is purely computational.</p><h3>The Insight: Divide and Conquer</h3><p>Think about how you’d solve this problem if you had eight friends and a whiteboard.</p><p>You wouldn’t hand all 10 million records to one person and tell the other seven to watch. You’d split the list into eight chunks, hand one to each person, let everyone work simultaneously, then add up the eight sub-totals at the end.</p><p>That’s it. That’s Fork/Join.</p><pre>10 million records<br>       ↓ split<br>[1.25M] [1.25M] [1.25M] [1.25M] [1.25M] [1.25M] [1.25M] [1.25M]<br>   ↓       ↓       ↓       ↓       ↓       ↓       ↓       ↓<br> sum     sum     sum     sum     sum     sum     sum     sum<br>                              ↓ merge<br>                         grand total</pre><p>Eight friends working in parallel takes 1/8th the time. Eight CPU cores working in parallel — in theory — takes 1/8th the time too.</p><p>The Fork/Join framework is Java’s implementation of this idea. “Fork” means split the problem into subproblems. “Join” means wait for all subproblems to finish and combine the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kl-yoAYMfavrd7kevdGa3g.png" /></figure><p><em>Figure: A recursive divide-and-conquer tree. A large task splits into smaller tasks, each splitting further until tasks are small enough to solve directly. Results merge back up the tree.</em></p><h3>Why Not Just Use a Regular Thread Pool?</h3><p>Fair question. You just learned about thread pools in Part 4. Why not submit 8 chunks to a ThreadPoolExecutor and wait for all of them?</p><p>For simple cases like summing numbers, you actually can — and it works fine. But Fork/Join was designed for a subtler problem: <strong>tasks that recursively split into subtasks of unknown depth.</strong></p><p>Imagine instead of summing, you’re traversing a file system tree — scanning directories, each of which might contain more directories. You don’t know upfront how deep the tree goes or how many files there are. You just know: “scan this directory, and for each subdirectory you find, scan that too.”</p><p>With a regular thread pool, you hit a wall quickly. A thread picks up “scan /home” and finds 20 subdirectories. It submits all 20 to the pool as new tasks and then… does what? If it blocks waiting for those 20 tasks to finish, it’s consuming a thread doing nothing. If the pool only has 8 threads and all 8 are blocked waiting for subtasks, and those subtasks need threads to run, you have a deadlock.</p><p>Fork/Join solves this with two innovations:</p><p><strong>1. Work stealing</strong></p><p>Each worker thread in a Fork/Join pool has its own double-ended task deque (deck). When a thread forks a subtask, it pushes it to the front of its own deque and continues working on something else. Idle threads don’t wait — they steal tasks from the <em>back</em> of other threads’ deques.</p><p>The result: no thread ever sits idle as long as there’s work to do, and there’s minimal contention because threads mostly work their own queue and only steal when empty.</p><p><strong>2. Managed blocking</strong></p><p>Fork/Join threads can signal the pool when they’re about to block, allowing the pool to compensate by spawning a spare thread. This prevents the pool from seizing up when tasks need to wait.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iwRJT6HS2N8g7S-Nh4biRw.png" /></figure><p><em>Figure: Each thread has its own deque. Threads push new subtasks to their own deque front and pop from the front. Idle threads steal from the back of other threads’ deques — minimal contention.</em></p><h3>The Code: RecursiveTask</h3><p>Fork/Join tasks extend either RecursiveTask&lt;T&gt; (returns a result) or RecursiveAction (no result). You implement one method: compute(). Inside, you decide: is this problem small enough to solve directly? If yes, solve it. If no, split it, fork the halves, join the results.</p><pre>import java.util.concurrent.RecursiveTask;<br>import java.util.List;<br><br>public class ShipmentSumTask extends RecursiveTask&lt;Double&gt; {<br>    private static final int THRESHOLD = 10_000;  // solve directly if ≤ 10K records<br>    private final List&lt;Shipment&gt; shipments;<br>    private final int start;<br>    private final int end;<br>    public ShipmentSumTask(List&lt;Shipment&gt; shipments, int start, int end) {<br>        this.shipments = shipments;<br>        this.start = start;<br>        this.end = end;<br>    }<br><br>    @Override<br>    protected Double compute() {<br>        int size = end - start;<br>        // Base case: small enough to compute directly<br>        if (size &lt;= THRESHOLD) {<br>            double sum = 0;<br>            for (int i = start; i &lt; end; i++) {<br>                sum += shipments.get(i).getAmount();<br>            }<br>            return sum;<br>        }<br>        // Recursive case: split in half, fork both, join results<br>        int mid = start + size / 2;<br>        ShipmentSumTask left  = new ShipmentSumTask(shipments, start, mid);<br>        ShipmentSumTask right = new ShipmentSumTask(shipments, mid, end);<br>        left.fork();               // submit left to pool asynchronously<br>        double rightResult = right.compute();  // compute right on THIS thread<br>        double leftResult  = left.join();      // wait for left to finish<br>        return leftResult + rightResult;<br>    }<br>}</pre><p>Running it:</p><pre>import java.util.concurrent.ForkJoinPool;<br><br>ForkJoinPool pool = new ForkJoinPool();  // default: one thread per CPU core<br>List&lt;Shipment&gt; shipments = loadAllShipments();  // 10 million records<br>ShipmentSumTask task = new ShipmentSumTask(shipments, 0, shipments.size());<br>double total = pool.invoke(task);<br>System.out.println(&quot;Total revenue: &quot; + total);</pre><p>Notice the pattern in compute(): fork left, then compute() right directly on the current thread (don&#39;t waste it), then join() left. This is the canonical Fork/Join idiom — one fork, one direct compute, one join. It keeps threads busy rather than having them all fork-and-wait.</p><h3>But Who Actually Writes RecursiveTask?</h3><p>Honest answer: almost nobody in application code.</p><p>Writing correct RecursiveTask implementations requires careful threshold tuning, correct fork/join ordering, and understanding of the pool&#39;s behavior. Get it wrong and you can actually make things slower than sequential code (task creation overhead exceeds the parallelism benefit for tasks that are too small).</p><p>The RecursiveTask API exists for library authors and framework developers who need precise control. For application developers, Java gives you something much simpler: <strong>parallel streams</strong>.</p><h3>Parallel Streams: Fork/Join Without the Boilerplate</h3><p>Remember the problem from the start of this article?</p><pre>// Sequential — uses one core, takes 47 seconds<br>double total = shipments.stream()<br>    .mapToDouble(Shipment::getAmount)<br>    .sum();<br><br>// Parallel - uses all cores, takes ~6 seconds on 8 cores<br>double total = shipments.parallelStream()<br>    .mapToDouble(Shipment::getAmount)<br>    .sum();</pre><p>One word: parallel. The stream framework automatically partitions your data, submits work to ForkJoinPool.commonPool(), executes in parallel, and merges the results. All the RecursiveTask machinery from above happens behind the scenes.</p><p>That’s it. The 47-second computation drops to ~6 seconds on an 8-core machine. Eight cores doing 1/8th of the work each.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iuSfGi6k_xO_KQFVTUTPkg.png" /></figure><p><em>Figure: Sequential stream: one thread, all elements processed left to right. Parallel stream: data split across CPU cores, each processing its chunk, results merged at the end.</em></p><h3>What happens under the hood</h3><p>When you call .parallelStream():</p><ol><li>The spliterator for your collection divides the data into chunks</li><li>Each chunk is submitted as a Fork/Join task to ForkJoinPool.commonPool()</li><li>Worker threads recursively split chunks further until each chunk is small enough to process directly</li><li>Intermediate results are combined (via the stream’s combiner function — sum, collect, etc.)</li><li>The final result is returned</li></ol><p>You don’t see any of this. You just write normal stream operations.</p><h3>The Three Questions to Ask Before Using parallelStream()</h3><p>Parallel streams sound like free performance. They’re not. Used incorrectly, they make things slower, produce wrong results, or cause subtle bugs. Before reaching for .parallelStream(), ask three questions.</p><h3>Question 1: Is the workload CPU-bound and large enough?</h3><p>Parallel streams shine when: the operation is computationally heavy (math, image processing, string manipulation, sorting), the data is large (hundreds of thousands of elements minimum), and there’s no I/O involved.</p><p>They don’t help — and actively hurt — when:</p><ul><li><strong>The collection is small.</strong> Thread coordination overhead exceeds the work. Splitting a 50-element list across 8 cores is slower than just iterating it on one thread.</li></ul><pre>// Fast sequentially, SLOWER with parallel (overhead &gt; benefit)<br>List&lt;Integer&gt; small = List.of(1, 2, 3, 4, 5);<br>int sum = small.parallelStream().mapToInt(Integer::intValue).sum();</pre><ul><li><strong>The work is I/O-bound.</strong> If each element requires a database call or HTTP request, parallel streams will block multiple ForkJoinPool threads simultaneously — starving other CompletableFutures sharing the common pool. Use CompletableFuture with a dedicated I/O thread pool instead.</li><li><strong>The work is trivially fast.</strong> Parallelizing x * 2 across 10 million elements might not be faster than sequential — the cost of splitting, coordinating, and merging can exceed the cost of the computation itself.</li></ul><p><strong>Rule of thumb:</strong> if your sequential stream takes less than a few milliseconds, don’t parallelize it. The overhead isn’t worth it.</p><h3>Question 2: Is your operation safe to run in parallel?</h3><p>Parallel streams run operations on multiple threads simultaneously. This means everything you learned in Parts 2 and 3 applies — shared mutable state will cause race conditions.</p><pre>// BUG: race condition — multiple threads write to the same list simultaneously<br>List&lt;String&gt; results = new ArrayList&lt;&gt;();<br>shipments.parallelStream()<br>    .map(Shipment::getTrackingNumber)<br>    .forEach(results::add);  // ArrayList is not thread-safe — data corruption<br><br>// CORRECT: collect into a thread-safe result<br>List&lt;String&gt; results = shipments.parallelStream()<br>    .map(Shipment::getTrackingNumber)<br>    .collect(Collectors.toList());  // collector handles thread safety</pre><p>The stream’s built-in terminal operations (collect, reduce, sum, count, findFirst) are safe for parallel use — they&#39;re designed with thread-safe combining. Rolling your own state inside forEach with a shared mutable container is not.</p><p>Also avoid operations with side effects that depend on order:</p><pre>// BUG: order of prints is unpredictable with parallel<br>shipments.parallelStream()<br>    .forEach(s -&gt; System.out.println(s.getId()));  // prints in arbitrary order<br><br>// OK if order doesn&#39;t matter; use forEachOrdered if it does (slower)<br>shipments.parallelStream()<br>    .forEachOrdered(s -&gt; System.out.println(s.getId()));  // sequential order guaranteed</pre><h3>Question 3: Are you using the right pool?</h3><p>parallelStream() uses ForkJoinPool.commonPool() by default. This pool is shared by every parallel stream in your entire JVM — including streams in libraries you didn&#39;t write. A long-running parallel computation in one part of your app can starve parallel streams in another.</p><p>To use a custom pool:</p><pre>ForkJoinPool customPool = new ForkJoinPool(4);  // 4 threads instead of all cores<br><br>double total = customPool.submit(() -&gt;<br>    shipments.parallelStream()<br>        .mapToDouble(Shipment::getAmount)<br>        .sum()<br>).get();</pre><p>This is a lesser-known trick — submitting the parallel stream operation as a task to a specific ForkJoinPool. The stream will use that pool&#39;s threads rather than the common pool. Essential when you need to isolate parallel workloads from each other.</p><h3>A Practical Decision Guide</h3><p>You now have three tools for concurrent work: CompletableFuture, parallel streams, and Fork/Join directly. Here’s when to reach for each:</p><pre>What kind of work?<br>      ↓<br>Is it I/O-bound?<br>(database, HTTP, file, network)<br>      ↓ YES<br>Use CompletableFuture with a dedicated thread pool.<br>Don&#39;t use parallel streams — they&#39;ll block ForkJoinPool threads.<br>      ↓ NO (CPU-bound)<br>Is it a standard collection operation?<br>(map, filter, reduce, collect, sort)<br>      ↓ YES<br>Use .parallelStream() - simple, built-in, handles splitting automatically.<br>Only if: large data (100K+ elements), operation is meaningfully expensive per element.<br>      ↓ NO (custom recursive computation)<br>Do you need recursive divide-and-conquer?<br>(file system traversal, tree processing, custom merge sort)<br>      ↓ YES<br>Use RecursiveTask / RecursiveAction directly.<br>      ↓ NO<br>Are you sure you need parallelism?<br>Maybe the answer is just a faster algorithm.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XH36Us6Nvs6_AaGmLtCfZg.png" /></figure><p><em>Figure: Choosing the right concurrent tool. I/O-bound → CompletableFuture. CPU-bound standard collection ops → parallel streams. CPU-bound recursive custom → RecursiveTask.</em></p><h3>The Gotchas Nobody Warns You About</h3><h3>Gotcha 1: Parallel doesn’t always mean faster</h3><p>This bears repeating because engineers consistently overestimate parallelism gains. Amdahl’s Law: if 10% of your computation is inherently sequential (can’t be parallelized), then even with infinite cores, you’ll never go faster than 10x. In practice, the coordination overhead of splitting and merging often means the real speedup is much less than the number of cores.</p><p>Always measure. Don’t assume.</p><h3>Gotcha 2: Stateful lambdas in parallel streams</h3><pre>// BUG: stateful lambda — result depends on execution order<br>int[] counter = {0};<br>List&lt;Integer&gt; results = shipments.parallelStream()<br>    .map(s -&gt; {<br>        counter[0]++;              // shared mutable state — race condition<br>        return s.getAmount() * counter[0];<br>    })<br>    .collect(Collectors.toList());</pre><p>Stream operations must be stateless — they should not depend on or modify any state that changes during pipeline execution. In sequential streams, this sometimes “works” accidentally. In parallel streams, it immediately produces wrong results.</p><h3>Gotcha 3: Parallel stream with sorted() or distinct() is often slower than sequential</h3><p>sorted() and distinct() require seeing all elements before producing output — they&#39;re inherently sequential operations. When you put them in a parallel stream, the framework parallelizes what it can, then serializes at the sort/distinct step, then might parallelize again. The parallelization-then-serialization overhead often makes this slower than a plain sequential stream.</p><pre>// Possibly slower than sequential for large datasets<br>List&lt;Shipment&gt; result = shipments.parallelStream()<br>    .filter(s -&gt; s.getAmount() &gt; 1000)<br>    .sorted(Comparator.comparing(Shipment::getDate))  // serializes here<br>    .collect(Collectors.toList());</pre><h3>Gotcha 4: Blocking operations in parallelStream() starve the pool</h3><pre>// BUG: database call inside parallelStream blocks ForkJoinPool threads<br>List&lt;OrderDetail&gt; details = orderIds.parallelStream()<br>    .map(id -&gt; database.findById(id))  // blocking I/O on ForkJoinPool thread!<br>    .collect(Collectors.toList());</pre><p>ForkJoinPool.commonPool() has N_cpu - 1 threads. If each one blocks on a database call, the pool is full of sleeping threads. No other parallel stream or Fork/Join computation can proceed until these sleeping threads wake up. The whole application stalls.</p><p>For I/O inside what looks like a CPU operation, use CompletableFuture:</p><pre>// CORRECT: CompletableFuture with IO pool for blocking operations<br>ExecutorService ioPool = Executors.newFixedThreadPool(20);<br><br>List&lt;CompletableFuture&lt;OrderDetail&gt;&gt; futures = orderIds.stream()<br>    .map(id -&gt; CompletableFuture.supplyAsync(() -&gt; database.findById(id), ioPool))<br>    .collect(Collectors.toList());<br>List&lt;OrderDetail&gt; details = futures.stream()<br>    .map(CompletableFuture::join)<br>    .collect(Collectors.toList());</pre><h3>Back to Monday Morning</h3><p>Remember the 47-second problem from the start? With everything you now know:</p><pre>// Option 1: parallel stream — simplest, uses all CPU cores<br>double total = shipments.parallelStream()<br>    .mapToDouble(Shipment::getAmount)<br>    .sum();<br>// ~6 seconds on 8 cores. Done.<br><br>// Option 2: parallel stream with custom pool - isolated from other workloads<br>ForkJoinPool pool = new ForkJoinPool(8);<br>double total = pool.submit(() -&gt;<br>    shipments.parallelStream()<br>        .mapToDouble(Shipment::getAmount)<br>        .sum()<br>).get();<br>// Same speed, but doesn&#39;t share the common pool.<br>// Option 3: RecursiveTask - maximum control, not needed here<br>// (parallel stream handles this case perfectly)</pre><p>Your manager gets the number. By 9am, not noon.</p><p>The lesson isn’t “always use parallel streams.” The lesson is understanding when parallelism helps (CPU-bound, large data, no shared state) and when it doesn’t (I/O-bound, small data, stateful operations) — so you can reach for the right tool without guessing.</p><h3>Summary</h3><p>Tool Best for Watch out for parallelStream() CPU-bound collection ops on large data Small collections, I/O inside the lambda, shared state RecursiveTask Custom recursive divide-and-conquer Overkill for standard ops — use parallel streams instead ForkJoinPool (custom) Isolating parallel work from commonPool Overhead of managing the pool lifecycle <strong>Don&#39;t parallelize when</strong> Work is I/O-bound, data is small, or op is trivially fast Parallel overhead can exceed benefit</p><p>Fork/Join and parallel streams are not general-purpose concurrency tools. They’re a specific solution to a specific problem: <strong>making full use of multiple CPU cores for computation-heavy work</strong>. When that’s your problem, they’re the right answer. When your problem is something else — waiting for databases, coordinating services, handling requests — the other tools in this series are better fits.</p><p><em>Next in the series: Part 7 — Virtual Threads &amp; Structured Concurrency. Java 21 introduced virtual threads — a fundamentally different threading model that collapses the distinction between “use a big thread pool for I/O” and “use a small pool for CPU.” It changes the calculus of everything you’ve learned so far. And structured concurrency gives you a way to reason about groups of concurrent tasks that the older APIs never could. This is where Java concurrency gets genuinely exciting again.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f34d44ebc80" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Concurrency & Async: The Complete Picture]]></title>
            <link>https://medium.com/@rajatraghav7797/java-concurrency-async-the-complete-picture-6e2219214f4e?source=rss-d50c9c063b6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e2219214f4e</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <dc:creator><![CDATA[Rajat Kumar]]></dc:creator>
            <pubDate>Fri, 07 Aug 2026 18:58:17 GMT</pubDate>
            <atom:updated>2026-08-07T18:59:05.037Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 5 — CompletableFuture: Building Non-Blocking Async Pipelines</h3><p><em>Part of the series: Java Concurrency &amp; Async — The Complete Picture</em></p><p>In the previous article [<a href="https://medium.com/@rajatraghav7797/java-concurrency-async-the-complete-picture-0a9e0a77bedf?sharedUserId=rajatraghav7797"><strong><em>LINK</em></strong></a>], we explored ExecutorService and Future&lt;T&gt;. We learned how thread pools help us execute tasks asynchronously and how Future lets us retrieve the result once the task finishes.</p><p>At first glance, it feels like we’ve solved asynchronous programming. Need to execute a task on another thread? Submit it to a thread pool. Need the result later? Call future.get().</p><p>Simple.</p><p>But the moment you start building real backend services, Future begins to show its limitations.</p><p>Imagine you’re building the backend for an e-commerce website. A customer opens the <strong>Order Summary</strong> page, and your API needs to collect information from several independent services before it can respond.</p><ul><li>User Profile Service</li><li>Order History Service</li><li>Recommendation Service</li></ul><p>Each service takes roughly <strong>100 ms</strong> to respond. Your first instinct might be to execute them one after another.</p><pre>Fetch User<br>    ↓ 100 ms<br>Fetch Orders<br>    ↓ 100 ms<br>Fetch Recommendations<br>    ↓ 100 ms<br>Return Response<br><br>Total Latency ≈ 300 ms</pre><p>That’s unnecessarily slow because none of these operations depend on each other. Instead, we can execute all three simultaneously.</p><pre>User Service  ───────┐<br>                     │<br>Orders Service ──────┼──► Build Response<br>                     │<br>Recommendations ─────┘<br><br>Total Latency ≈ 100 ms<br></pre><p>Thread pools and Future make this possible.</p><pre>Future&lt;User&gt; userFuture =<br>        pool.submit(() -&gt; fetchUser(userId));<br><br>Future&lt;List&lt;Order&gt;&gt; ordersFuture =<br>        pool.submit(() -&gt; fetchOrders(userId));<br><br>Future&lt;List&lt;Product&gt;&gt; recommendationFuture =<br>        pool.submit(() -&gt; fetchRecommendations(userId));</pre><p>So far, everything looks great. Now comes the problem.</p><pre>User user = userFuture.get();<br>List&lt;Order&gt; orders = ordersFuture.get();<br>List&lt;Product&gt; recommendations = recommendationFuture.get();</pre><p>The moment we call get(), the calling thread stops doing useful work and waits. If the user service is still processing the request, our thread simply sits there doing nothing. It isn’t computing. It isn’t serving another request. It isn’t progressing the program. It’s just waiting. That may not sound like a big problem for a single request.</p><p>But imagine hundreds or even thousands of concurrent requests hitting your application. Suddenly, you have hundreds of threads whose only job is to wait. This is the biggest limitation of Future. It can execute work asynchronously, but <strong>consuming the result is still fundamentally synchronous</strong>. As applications grow more complex, this limitation becomes increasingly painful.</p><p>Suppose you need to:</p><ul><li>Fetch a user.</li><li>Then fetch that user’s orders.</li><li>Then calculate the total amount spent.</li><li>Meanwhile, fetch recommendations in parallel.</li><li>Combine everything into one response.</li><li>Recover gracefully if one service fails.</li><li>Abort the request if a service takes longer than three seconds.</li></ul><p>Doing all of this with plain Future quickly turns into nested code, manual coordination, blocking calls, and difficult error handling. Java 8 introduced <strong>CompletableFuture</strong> to solve exactly these problems. Instead of asking,</p><blockquote><em>“Is the result ready yet?”</em></blockquote><p>you describe</p><blockquote><strong><em>“When the result is ready, here’s what should happen next.”</em></strong></blockquote><p>That small shift completely changes how asynchronous programs are written. Instead of waiting for results, we build <strong>pipelines</strong>. Instead of blocking threads, we compose stages. Instead of writing synchronous-looking asynchronous code, we let the runtime trigger the next step automatically as soon as the previous one finishes.</p><p>By the end of this article, you’ll understand how to build those pipelines using CompletableFuture, how every major API fits into that model, and more importantly, <strong>when to use each one in real production applications.</strong></p><h3>What Does “Non-Blocking” Actually Mean?</h3><p>You’ll often hear developers describe CompletableFuture as <em>non-blocking</em>. While that&#39;s technically correct, it&#39;s also one of the most misunderstood phrases in Java concurrency.</p><p>Many developers hear <strong>non-blocking</strong> and imagine that no thread is involved. That’s not true. A CompletableFuture doesn&#39;t magically eliminate threads. It simply changes <strong>which thread waits</strong>.</p><p>Let’s revisit our previous example.</p><pre>Future&lt;User&gt; future = pool.submit(() -&gt; fetchUser(userId));<br>User user = future.get();   // blocks<br>processUser(user);</pre><p>Here’s what happens behind the scenes.</p><ol><li>The main thread submits the task to the thread pool.</li><li>A worker thread starts executing fetchUser().</li><li>The main thread immediately calls future.get().</li><li>Since the worker hasn’t finished yet, the main thread goes to sleep and waits.</li><li>When the worker completes, the main thread wakes up and continues.</li></ol><p>The worker thread was busy doing useful work. The main thread wasn’t. It spent that entire time waiting. Think of it like ordering food at a restaurant. You place your order and then decide to stand at the kitchen entrance until your food is ready. You aren’t cooking. You aren’t eating. You’re just waiting.</p><p>That’s exactly what future.get() does. Now imagine a different approach. You place your order. Instead of standing outside the kitchen, you go talk to your friends. When your food is ready, the waiter comes to your table and serves it. You never wasted time standing around. This is the mindset behind CompletableFuture. Instead of continuously asking,</p><blockquote><em>“Is my result ready?”</em></blockquote><p>you tell Java,</p><blockquote><em>“When the result is ready, execute this code.”</em></blockquote><p>The waiting still happens. The network request still takes time. The database query still executes on another thread. The difference is that <strong>your calling thread is free to continue doing other work instead of sitting idle.</strong></p><p>This is the key idea behind non-blocking programming. It doesn’t make operations faster. It makes your application <strong>more efficient</strong> by ensuring threads spend more time working and less time waiting.</p><h3>Future vs CompletableFuture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LgbXv50ohBs6dVKklqk4og.png" /></figure><p>Those external systems are slow. Your CPU isn’t. Blocking valuable application threads while waiting for those systems is simply a waste of resources. CompletableFuture doesn&#39;t reduce the time taken by the database or network. It reduces the amount of <strong>idle waiting performed by your application’s threads</strong>.</p><p>That’s the real meaning of <strong>non-blocking</strong>.</p><h3>Creating Your First CompletableFuture</h3><p>Just like ExecutorService, a CompletableFuture also needs somewhere to execute its work. The simplest way to create one is using supplyAsync().</p><pre>CompletableFuture&lt;User&gt; userFuture =<br>        CompletableFuture.supplyAsync(() -&gt; fetchUser(userId));</pre><p>Let’s break this down.</p><ul><li>fetchUser(userId) is the task we want to execute.</li><li>supplyAsync() submits that task to a thread pool.</li><li>Instead of returning the actual User, it immediately returns a CompletableFuture&lt;User&gt;.</li></ul><p>Notice something important. The following line <strong>does not wait</strong> for fetchUser() to finish.</p><pre>CompletableFuture&lt;User&gt; userFuture =<br>        CompletableFuture.supplyAsync(() -&gt; fetchUser(userId));<br><br>System.out.println(&quot;Main thread continues...&quot;);</pre><p>As soon as the task is submitted, the calling thread moves on. Meanwhile, another thread starts executing fetchUser() in the background. This is the first major difference from writing synchronous code. In synchronous programming, the next line cannot execute until the current method finishes.</p><pre>User user = fetchUser(userId);   // blocks<br>System.out.println(&quot;Done&quot;);</pre><p>The program waits for fetchUser() before printing &quot;Done&quot;. With CompletableFuture, the execution order changes.</p><pre>CompletableFuture&lt;User&gt; future =<br>        CompletableFuture.supplyAsync(() -&gt; fetchUser(userId));<br>System.out.println(&quot;Done&quot;);</pre><p>Output:</p><pre>Done</pre><p>A little later…</p><pre>fetchUser() completed</pre><p>The asynchronous task continues running independently while the calling thread is already free to perform other work. This is why you’ll often hear people say that a CompletableFuture represents <strong>a promise of a future result</strong>.</p><p>You don’t have the User yet. You only have an object that promises,</p><blockquote><em>“I’ll eventually contain a </em><em>User.&quot;</em></blockquote><h3>runAsync() vs supplyAsync()</h3><p>There are two factory methods you’ll use most often.</p><h4>runAsync()</h4><p>Use this when your task <strong>doesn’t return anything</strong>.</p><pre>CompletableFuture&lt;Void&gt; future =<br>        CompletableFuture.runAsync(() -&gt; sendEmail(user));</pre><p>Typical use cases include:</p><ul><li>Sending emails</li><li>Writing audit logs</li><li>Clearing caches</li><li>Publishing events</li><li>Background cleanup jobs</li></ul><p>The task performs work but doesn’t produce a value for later stages.</p><h4>supplyAsync()</h4><p>Use this when your task <strong>returns a result</strong>.</p><pre>CompletableFuture&lt;User&gt; future =<br>        CompletableFuture.supplyAsync(() -&gt; fetchUser(userId));</pre><p>Most backend service calls fall into this category because you’re usually retrieving data from somewhere.</p><p>For example:</p><ul><li>Fetch a customer</li><li>Load products</li><li>Read from Redis</li><li>Execute a database query</li><li>Call another microservice</li></ul><p>Each operation eventually produces a value that later stages can use.</p><h3>Which Thread Executes supplyAsync()?</h3><p>This is a question that often confuses developers.</p><p>When you write</p><pre>CompletableFuture&lt;User&gt; future =<br>        CompletableFuture.supplyAsync(() -&gt; fetchUser(userId));</pre><p>two threads are involved.</p><pre>Main Thread<br>    │<br>    ├── Creates CompletableFuture<br>    ├── Submits task<br>    └── Continues immediately<br></pre><pre>Worker Thread<br>    │<br>    ├── Executes fetchUser()<br>    └── Completes the future</pre><p>The lambda passed to supplyAsync() <strong>does not execute on the calling thread</strong>. It executes on a worker thread obtained from an executor. By default, if you don’t specify an executor, Java uses the <strong>ForkJoinPool.commonPool()</strong>.</p><pre>CompletableFuture&lt;User&gt; future =<br>        CompletableFuture.supplyAsync(() -&gt; fetchUser(userId));</pre><p>Although convenient for small examples, this isn’t what you should rely on in production systems.</p><h3>Why You Should Avoid the Common Pool</h3><p>The common pool is shared across the entire JVM. That means your application code, third-party libraries, and framework internals may all compete for the same worker threads. Now imagine one part of your application performs a slow database query or waits for an external REST API. Those worker threads remain occupied while waiting for I/O.</p><p>Soon enough, unrelated tasks submitted by other parts of the application also start waiting because there are no free workers available. This kind of resource contention is difficult to diagnose and often leads to unpredictable latency under load. Instead, create an executor dedicated to the type of work you’re performing.</p><pre>ExecutorService ioPool = Executors.newFixedThreadPool(20);<br><br>CompletableFuture&lt;User&gt; future =<br>        CompletableFuture.supplyAsync(<br>                () -&gt; fetchUser(userId),<br>                ioPool);</pre><p>Now your asynchronous pipeline runs on threads that belong only to your application. You control their size, lifecycle, and workload instead of sharing them with everything else running inside the JVM.</p><p>As a general rule, <strong>production applications should almost always provide their own executor rather than relying on the common pool.</strong></p><h3>Building an Async Pipeline</h3><p>So far, we’ve learned that CompletableFuture immediately returns a placeholder for a future result. But that raises an obvious question.</p><p>If we never call future.get(), <strong>how do we actually use the value once it&#39;s becomes available?</strong></p><p>The answer is surprisingly simple. Instead of waiting for the result, we <strong>attach the next step</strong>. Think of an assembly line in a factory.</p><p>A product moves from one station to the next.</p><ul><li>Station 1 assembles the parts.</li><li>Station 2 paints them.</li><li>Station 3 performs quality checks.</li><li>Station 4 packages the product.</li></ul><p>Each station starts working only after the previous one has finished. Nobody waits around asking,</p><blockquote><em>“Is the previous stage done yet?”</em></blockquote><p>The next stage simply begins automatically when the previous one completes. CompletableFuture works exactly the same way. Each operation creates a <strong>new stage</strong> in an asynchronous pipeline. When one stage finishes, Java automatically triggers the next one. No polling. No manual coordination. No repeated calls to get().</p><p>Let’s build our first pipeline.</p><pre>CompletableFuture&lt;String&gt; future =<br>        CompletableFuture.supplyAsync(() -&gt; fetchUser(userId))<br>                .thenApply(User::getName)<br>                .thenApply(String::toUpperCase);<br>future.thenAccept(System.out::println);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GzvkqLYew1na91xt4A2erg.png" /></figure><blockquote><em>“Has the user finished loading?”</em></blockquote><p>We simply described <strong>what should happen next</strong>. Java takes care of executing each stage when the previous one completes. This is why CompletableFuture pipelines often feel much more natural than writing explicit synchronization code.</p><h3>thenApply() — Transform the Result</h3><p>The most commonly used stage is thenApply(). Its job is simple. It takes the result from the previous stage, transforms it into something else, and returns a <strong>new </strong><strong>CompletableFuture</strong> containing that transformed value. For example, suppose fetchUser() returns a complete User object.</p><pre>CompletableFuture&lt;User&gt; future =<br>        CompletableFuture.supplyAsync(() -&gt; fetchUser(userId));</pre><p>But perhaps the next stage only needs the user’s name.</p><pre>CompletableFuture&lt;String&gt; nameFuture =<br>        future.thenApply(User::getName);</pre><p>Nothing blocks. Nothing waits. As soon as the User becomes available, Java automatically invokes getName() and produces a new future containing the String. The original future still contains a User. The new future contains a String. This is why every stage returns another CompletableFuture. Each transformation creates a brand-new stage in the pipeline. You can continue chaining transformations as long as you like.</p><pre>CompletableFuture&lt;String&gt; future =<br>        CompletableFuture<br>                .supplyAsync(() -&gt; fetchUser(userId))<br>                .thenApply(User::getName)<br>                .thenApply(String::trim)<br>                .thenApply(String::toUpperCase);</pre><p>Rather than thinking about threads, think about <strong>data flowing through a pipeline</strong>.</p><pre>User<br>   │<br>   ▼<br>Name<br>   │<br>   ▼<br>Trimmed Name<br>   │<br>   ▼<br>Uppercase Name</pre><p>Every stage receives the output of the previous stage and produces the input for the next.</p><h3>thenAccept() — Consume the Result</h3><p>Sometimes you don’t want to transform the value. You simply want to <strong>use</strong> it. That’s where thenAccept() comes in.</p><pre>CompletableFuture<br>        .supplyAsync(() -&gt; fetchUser(userId))<br>        .thenAccept(user -&gt;<br>                log.info(&quot;Fetched {}&quot;, user.getName()));</pre><p>Unlike thenApply(), thenAccept() doesn&#39;t produce another value. It simply performs an action.</p><p>Typical examples include:</p><ul><li>Logging</li><li>Sending a notification</li><li>Updating a cache</li><li>Writing audit records</li><li>Publishing an event</li></ul><p>Think of it as the <strong>end of a pipeline</strong> where the result is consumed instead of transformed.</p><h3>thenRun() — Execute Something After Completion</h3><p>Occasionally, you don’t even care about the result. You simply want to execute another task after the previous stage finishes. That’s exactly what thenRun() does.</p><pre>CompletableFuture<br>        .supplyAsync(() -&gt; processOrder(orderId))<br>        .thenRun(() -&gt;<br>                metrics.increment(&quot;orders.processed&quot;));</pre><p>Notice that the lambda receives no arguments. It doesn’t know what the previous stage returned. It only knows that the previous stage has completed successfully.</p><p>This makes it useful for tasks like:</p><ul><li>Updating metrics</li><li>Cleaning temporary resources</li><li>Triggering background maintenance</li><li>Starting another independent operation</li></ul><h3>Choosing the Right Stage</h3><p>These three methods look similar, but they solve different problems.</p><p>If you want to…UseTransform the result into another valuen thenApply()Consume the result without returning anything thenAccept()Execute another task without using the result.</p><p>thenRun() One way to remember them is to think about what happens to the data.</p><pre>Hava a result<br>      │</pre><pre>      ▼</pre><pre>Need another value?</pre><pre>      │</pre><pre>   Yes ─────────► thenApply()</pre><pre>      │</pre><pre>      No</pre><pre>      ▼</pre><pre>Need the value?</pre><pre>      │</pre><pre> Yes ───────────► thenAccept()</pre><pre>      │</pre><pre>      No</pre><pre>      ▼</pre><pre>thenRun()</pre><p>Once you become comfortable with these three methods, you’ll notice something interesting. Every one of them assumes the next step is <strong>synchronous</strong>. But what if the next step is <strong>another asynchronous operation</strong>? What if, after fetching the user, you need to asynchronously fetch their orders? That’s where one of the most important methods in the entire API enters the picture:</p><p><strong>thenCompose()</strong>.</p><h3>Chaining Asynchronous Operations with thenCompose()</h3><p>So far, every stage we’ve built has been <strong>synchronous</strong>. For example, after fetching a user, extracting their name is just a simple method call.</p><pre>CompletableFuture&lt;String&gt; future =<br>        CompletableFuture.supplyAsync(() -&gt; fetchUser(userId))<br>                .thenApply(User::getName);</pre><p>The transformation happens immediately. But real applications are rarely this simple. Imagine you’re building an Order Summary API. The first service returns the user.</p><pre>User user = fetchUser(userId);</pre><p>Now suppose you need to fetch that user’s orders. Can you call another service? Of course.</p><pre>List&lt;Order&gt; orders = fetchOrders(user.getId());</pre><p>But wait. fetchOrders() is another network call. It might take hundreds of milliseconds. If we’re building an asynchronous pipeline, we don’t want to execute it synchronously. Instead, we want another asynchronous operation.</p><pre>CompletableFuture&lt;List&lt;Order&gt;&gt; fetchOrders(Long userId)</pre><p>Now we have an interesting problem. The previous stage gives us a User. The next stage returns <strong>another </strong><strong>CompletableFuture</strong>.</p><h3>The Tempting Solution</h3><p>Our first instinct is usually to write this.</p><pre>CompletableFuture&lt;CompletableFuture&lt;List&lt;Order&gt;&gt;&gt; ordersFuture =<br>        CompletableFuture<br>                .supplyAsync(() -&gt; fetchUser(userId))<br>                .thenApply(user -&gt; fetchOrders(user.getId()));</pre><p>At first glance, this looks reasonable. But look carefully at the return type.</p><pre>CompletableFuture&lt;CompletableFuture&lt;List&lt;Order&gt;&gt;&gt;</pre><p>A future…. that contains another future. This is known as a <strong>nested future</strong>.</p><p>Instead of receiving the actual list of orders, you receive another promise that <em>might</em> eventually contain those orders. Now imagine continuing the pipeline.</p><pre>Future<br>    ↓<br>Future<br>    ↓<br>Future</pre><p>Things quickly become difficult to read and even harder to maintain. Fortunately, CompletableFuture has a solution.</p><h3>thenCompose() to the Rescue</h3><p>Whenever the next stage already returns another CompletableFuture, use thenCompose() instead of thenApply().</p><pre>CompletableFuture&lt;List&lt;Order&gt;&gt; ordersFuture =<br>        CompletableFuture<br>                .supplyAsync(() -&gt; fetchUser(userId))<br>                .thenCompose(user -&gt; fetchOrders(user.getId()));</pre><p>Notice the difference. The result is now simply</p><pre>CompletableFuture&lt;List&lt;Order&gt;&gt;</pre><p>No nesting. No extra wrapping. No additional unwrapping. thenCompose() automatically <strong>flattens</strong> the two futures into one continuous asynchronous pipeline.</p><h3>Think of It Like Connecting Pipes</h3><p>Imagine water flowing through a pipeline. With thenApply(), each stage simply changes the water flowing through it.</p><pre>User<br>   │<br>   ▼<br>Name<br>   │<br>   ▼<br>Uppercase Name</pre><p>The pipeline stays continuous. Now imagine the next stage doesn’t return water. Instead, it returns <strong>another pipeline</strong>. If we simply connect the first pipeline to the second without any adjustment, we end up with a pipe connected to… another entire pipe system. That’s essentially what happens with nested futures. thenCompose() solves this by joining both pipelines into one longer pipeline.</p><p>The flow becomes seamless.</p><pre>Fetch User<br>      │<br>      ▼<br>Fetch Orders<br>      │<br>      ▼<br>Calculate Total<br>      │<br>      ▼<br>Return Response</pre><p>The application behaves as if everything were one continuous asynchronous workflow.</p><h3>thenApply() vs thenCompose()</h3><p>A simple rule can help you decide which one to use.</p><h3>Use thenApply()</h3><p>When the next stage returns <strong>a normal value</strong>.</p><pre>.thenApply(User::getName)<br><br>User<br>   ↓<br>String</pre><h3>Use thenCompose()</h3><p>When the next stage returns <strong>another </strong><strong>CompletableFuture</strong>.</p><pre>.thenCompose(user -&gt; fetchOrders(user.getId()))<br><br>User<br>   ↓<br>CompletableFuture&lt;List&lt;Order&gt;&gt;</pre><h3>A Practical Example</h3><p>Let’s build a simple workflow.</p><ol><li>Fetch the user.</li><li>Fetch the user’s orders.</li><li>Calculate the total amount spent.</li><li>Display the result.</li></ol><pre>CompletableFuture&lt;Double&gt; totalSpent =<br>        CompletableFuture<br>                .supplyAsync(() -&gt; fetchUser(userId))<br>                .thenCompose(user -&gt; fetchOrders(user.getId()))<br>                .thenApply(this::calculateTotal);</pre><p>Read it like an English sentence.</p><blockquote><em>Fetch the user…</em></blockquote><p>↓</p><blockquote><em>When the user arrives, asynchronously fetch their orders…</em></blockquote><p>↓</p><blockquote><em>When the orders arrive, calculate the total…</em></blockquote><p>No thread blocks. No polling. No nested futures. Each stage automatically begins when the previous one finishes.</p><h3>A Helpful Way to Remember</h3><p>You don’t need to memorize method names. Just ask yourself one question.</p><blockquote><strong><em>Does my lambda return a normal object or another </em></strong><strong><em>CompletableFuture?</em></strong></blockquote><p>If it returns:</p><ul><li>User</li><li>String</li><li>Integer</li><li>OrderSummary</li></ul><p>→ Use <strong>thenApply()</strong></p><p>If it returns:</p><ul><li>CompletableFuture&lt;User&gt;</li><li>CompletableFuture&lt;List&lt;Order&gt;&gt;</li><li>CompletableFuture&lt;Response&gt;</li></ul><p>→ Use <strong>thenCompose()</strong></p><p>That’s the only distinction you need to remember.</p><p>At this point, we’ve learned how to build <strong>sequential asynchronous workflows</strong>. Each stage waits for the previous stage to finish. But what if two tasks don’t depend on each other at all? Should one wait for the other?</p><p>Of course not. If two operations are independent, we should execute them <strong>in parallel</strong>. That’s exactly what the next set of APIs — thenCombine(), allOf(), and anyOf()—allow us to do.</p><h3>Running Independent Tasks in Parallel</h3><p>So far, every pipeline we’ve built has one thing in common.</p><p>Each stage depends on the result of the previous stage.</p><pre>Fetch User<br>     ↓<br>Fetch Orders<br>     ↓<br>Calculate Total</pre><p>This is a <strong>sequential dependency</strong>.</p><p>You can’t fetch a user’s orders until you know which user you’re dealing with. In such cases, thenCompose() is exactly what we need. But many real-world applications don’t follow a single chain of dependent operations.</p><p>Let’s go back to our <strong>Order Summary API</strong>.</p><p>To build the response, we need information from multiple services.</p><ul><li>User Profile</li><li>Order History</li><li>Product Recommendations</li></ul><p>These services are completely independent. The Recommendation Service doesn’t need the user’s order history. The User Service doesn’t need the recommendations. None of them depend on each other. If we execute them one after another, we’re wasting time.</p><pre>User Service<br>     ↓ 100 ms<br>Order Service<br>     ↓ 100 ms<br>Recommendation Service<br>     ↓ 100 ms<br>Total ≈ 300 ms<br></pre><p>Instead, we should start all three requests simultaneously.</p><pre>User Service ─────────┐<br>                      │<br>Order Service ────────┼──► Build Response<br>                      │<br>Recommendation ───────┘<br><br>Total ≈ 100 ms</pre><p>This is where CompletableFuture truly begins to shine. Instead of creating one long asynchronous chain, we can execute multiple independent tasks at the same time and combine their results later.</p><h3>Running Multiple Tasks Together</h3><p>Starting independent tasks is straightforward.</p><pre>CompletableFuture&lt;User&gt; userFuture =<br>        CompletableFuture.supplyAsync(() -&gt; fetchUser(userId), ioPool);<br><br>CompletableFuture&lt;List&lt;Order&gt;&gt; ordersFuture =<br>        CompletableFuture.supplyAsync(() -&gt; fetchOrders(userId), ioPool);<br>CompletableFuture&lt;List&lt;Product&gt;&gt; recommendationsFuture =<br>        CompletableFuture.supplyAsync(<br>                () -&gt; fetchRecommendations(userId),<br>                ioPool);</pre><p>Notice something important. We never wait after creating each future. All three tasks start almost immediately and execute concurrently on different worker threads. Now the question becomes,</p><blockquote><em>“How do we combine the results?”</em></blockquote><p>The answer depends on what we’re trying to achieve. Sometimes we need <strong>two results</strong>. Sometimes we need <strong>all results</strong>. Sometimes <strong>the first completed result</strong> is enough. CompletableFuture provides a different API for each scenario. Let’s look at them one by one.</p><h3>thenCombine() — Combine Two Independent Results</h3><p>Suppose our response only needs the user profile and order history. Both requests can run independently.</p><pre>CompletableFuture&lt;User&gt; userFuture =<br>        CompletableFuture.supplyAsync(() -&gt; fetchUser(userId), ioPool);<br><br>CompletableFuture&lt;List&lt;Order&gt;&gt; ordersFuture =<br>        CompletableFuture.supplyAsync(() -&gt; fetchOrders(userId), ioPool);</pre><p>Once both finish, we can combine their results.</p><pre>CompletableFuture&lt;OrderSummary&gt; summaryFuture =<br>        userFuture.thenCombine(<br>                ordersFuture,<br>                OrderSummary::new<br>        );</pre><p>thenCombine() waits for <strong>both</strong> futures to complete. Only then does it invoke the combining function. You can think of it as a meeting point where two independent asynchronous paths merge into one.</p><pre>User Future ───────┐<br>                   │<br>                   ▼<br>              thenCombine()<br>                   │<br>Orders Future ─────┘<br>                   │<br>                   ▼<br>           Order Summary</pre><p>If one future finishes earlier, it simply waits until the other one is also complete.</p><h3>allOf() — Wait for Everything</h3><p>Real applications rarely involve just two services. Sometimes we need to wait for five, ten, or even twenty independent operations. Creating a long chain of thenCombine() calls quickly becomes difficult to read. That’s why CompletableFuture provides allOf().</p><pre>CompletableFuture&lt;Void&gt; allTasks =<br>        CompletableFuture.allOf(<br>                userFuture,<br>                ordersFuture,<br>                recommendationsFuture<br>        );</pre><p>allOf() creates a new CompletableFuture that completes only after <strong>every supplied future</strong> has finished. Notice its return type.</p><pre>CompletableFuture&lt;Void&gt;</pre><p>This often surprises developers. Why doesn’t it return all the results? The reason is that every future may contain a different type.</p><pre>CompletableFuture&lt;User&gt;<br><br>CompletableFuture&lt;List&lt;Order&gt;&gt;<br><br>CompletableFuture&lt;List&lt;Product&gt;&gt;</pre><p>Java can’t combine these into one generic collection without losing type safety. Instead, allOf() simply tells us,</p><blockquote><em>“Everything has finished.”</em></blockquote><p>We can then retrieve the individual results.</p><pre>CompletableFuture&lt;OrderSummary&gt; summaryFuture =<br>        CompletableFuture<br>                .allOf(<br>                        userFuture,<br>                        ordersFuture,<br>                        recommendationsFuture<br>                )<br>                .thenApply(ignored -&gt;<br>                        new OrderSummary(<br>                                userFuture.join(),<br>                                ordersFuture.join(),<br>                                recommendationsFuture.join()<br>                        ));</pre><p>Notice the use of join() here. This is one of the few places where calling join() is perfectly safe.</p><p>Why?</p><p>Because allOf() has already guaranteed that every future has completed successfully. The calls to join() return immediately without blocking.</p><h3>anyOf() — Use the First Result That Arrives</h3><p>Sometimes we don’t care about every result. We only need the first one. Imagine your application queries multiple cache servers. Whichever server responds first wins. The others can simply be ignored.</p><pre>CompletableFuture&lt;Object&gt; fastest =<br>        CompletableFuture.anyOf(<br>                cacheServer1,<br>                cacheServer2,<br>                cacheServer3<br>        );</pre><p>As soon as any supplied future completes, anyOf() completes as well. The remaining tasks continue running unless they’re explicitly cancelled.</p><p>This pattern is useful for:</p><ul><li>Multiple cache replicas</li><li>Multiple read replicas</li><li>Redundant external services</li><li>Fallback providers</li><li>Race strategies for reducing latency</li></ul><h3>Which One Should You Use?</h3><p>Each API solves a different problem. SituationAPICombine exactly two independent futuresthenCombine()Wait for every future to finishallOf()Continue with the first completed futureanyOf() Don’t think of these methods as different ways of doing the same thing. Each represents a different synchronization strategy. Understanding <strong>when</strong> to use each one is far more important than memorizing their method signatures.</p><p>At this point, we know how to create asynchronous pipelines and how to execute multiple operations in parallel. But real production systems have another unavoidable reality. <strong>Things fail. </strong>Databases become unavailable. REST APIs return errors. Network connections time out. If we don’t handle failures correctly, one exception can break the entire asynchronous pipeline.</p><p>That’s exactly what we’ll tackle next.</p><h3>Handling Errors in Asynchronous Pipelines</h3><p>So far, every example we’ve written has assumed that everything goes according to plan. The database responds. The REST API is available. The cache returns the value. Unfortunately, production systems don’t work that way. Services become unavailable. Network requests fail. Databases restart. Timeouts happen. If we don’t handle these failures properly, a single exception can terminate the entire asynchronous pipeline.</p><p>Let’s look at an example.</p><pre>CompletableFuture&lt;String&gt; future =<br>        CompletableFuture<br>                .supplyAsync(() -&gt; fetchUser(userId))<br>                .thenApply(User::getName)<br>                .thenApply(String::toUpperCase);<br><br>future.join();</pre><p>Everything works perfectly… until fetchUser() throws an exception. Maybe the database is down. Maybe the user service returns an HTTP 500. Maybe a network timeout occurs. The exception immediately propagates through the pipeline. The remaining stages never execute.</p><pre>fetchUser()<br><br>↓<br>❌ Exception<br>↓<br><br>Pipeline Stops<br>↓<br><br>thenApply() ❌ Skipped<br>↓<br><br>thenApply() ❌ Skipped</pre><p>Unlike synchronous code, you can’t simply surround each stage with a try-catch. The computation is happening on another thread. Instead, CompletableFuture provides dedicated APIs for handling failures. Let’s understand each one.</p><h3>exceptionally() — Recover from a Failure</h3><p>The simplest recovery mechanism is exceptionally(). It allows you to provide a fallback value if something goes wrong.</p><pre>CompletableFuture&lt;String&gt; future =<br>        CompletableFuture<br>                .supplyAsync(() -&gt; fetchUser(userId))<br>                .thenApply(User::getName)<br>                .exceptionally(ex -&gt; &quot;Unknown User&quot;);</pre><p>If every stage succeeds, the pipeline continues normally.</p><pre>User<br><br>↓<br><br>Name<br>↓<br><br>Result</pre><p>If any previous stage throws an exception, exceptionally() executes instead.</p><pre>Exception<br><br>↓<br>exceptionally()<br>↓<br>&quot;Unknown User&quot;</pre><p>Notice something important. The pipeline doesn’t fail anymore. It continues using the fallback value. This is extremely useful when dealing with optional or non-critical services.</p><p>Examples include:</p><ul><li>Default profile image</li><li>Anonymous username</li><li>Empty recommendation list</li><li>Cached configuration</li><li>Default currency</li></ul><p>Instead of failing the entire request, the application degrades gracefully.</p><h3>handle() — Process Both Success and Failure</h3><p>Sometimes we need more control.</p><p>Suppose we want to:</p><ul><li>process the successful result if everything works, or</li><li>generate a fallback response if an exception occurs.</li></ul><p>Instead of writing separate success and failure paths, handle() gives us both.</p><pre>CompletableFuture&lt;String&gt; future =<br>        CompletableFuture<br>                .supplyAsync(() -&gt; fetchUser(userId))<br>                .handle((user, ex) -&gt; {<br>                    if (ex != null) {<br>                        return &quot;Guest&quot;;<br>                    }<br>                    return user.getName();<br>                });</pre><p>Unlike exceptionally(), handle() always executes. Whether the previous stage succeeds or fails, handle() receives both:</p><ul><li>the result (if available)</li><li>the exception (if one occurred)</li></ul><p>You decide how to continue. Think of it as a junction where both roads meet.</p><pre>         Success<br>             │<br>             ▼<br>          handle()<br>             ▲<br>             │<br>         Exception</pre><p>This makes handle() ideal when you want a single place to decide how the pipeline should continue.</p><h3>whenComplete() — Observe Without Changing</h3><p>Sometimes you don’t want to recover from an error. You simply want to know that it happened.</p><p>Perhaps you need to:</p><ul><li>log the exception,</li><li>update monitoring dashboards,</li><li>publish metrics,</li><li>notify an alerting system.</li></ul><p>That’s exactly what whenComplete() is for.</p><pre>CompletableFuture<br>        .supplyAsync(() -&gt; fetchUser(userId))<br>        .whenComplete((user, ex) -&gt; {<br>            if (ex != null) {<br>                log.error(&quot;User lookup failed&quot;, ex);<br>            } else {<br>                log.info(&quot;Fetched {}&quot;, user.getName());<br>            }<br>        });</pre><p>Unlike handle(), whenComplete() does <strong>not</strong> replace the result. It simply observes what happened. If the pipeline was successful, it remains successful. If the pipeline failed, it remains failed. Think of it as a security camera. The camera records everything. It doesn’t change what happens.</p><h3>Understanding the Difference</h3><p>These three methods look similar, but their purpose is very different.</p><p>If you want to…UseReturn a fallback value after failureexceptionally()Continue differently for success or failurehandle()Log or observe without modifying the resultwhenComplete()</p><p>A useful way to remember them is this:</p><ul><li><strong>exceptionally() repairs the pipeline.</strong></li><li><strong>handle() rebuilds the pipeline.</strong></li><li><strong>whenComplete() only watches the pipeline.</strong></li></ul><h3>What Happens to Exceptions?</h3><p>One question often surprises developers.</p><p>What if we don’t handle the exception at all?</p><pre>CompletableFuture&lt;String&gt; future =<br>        CompletableFuture<br>                .supplyAsync(() -&gt; fetchUser(userId))<br>                .thenApply(User::getName);<br>future.join();</pre><p>If fetchUser() fails, the call to join() throws a CompletionException.</p><pre>try {<br>    future.join();<br>} catch (CompletionException ex) {<br>    log.error(&quot;Pipeline failed&quot;, ex.getCause());<br>}</pre><p>Notice the use of getCause(). join() doesn&#39;t throw the original exception directly. Instead, Java wraps it inside a CompletionException. This allows asynchronous exceptions to be propagated consistently through the pipeline. Whenever you’re debugging a failed CompletableFuture, the real exception is usually inside the cause.</p><h3>Best Practices for Error Handling</h3><p>A few simple guidelines can make asynchronous code much easier to maintain.</p><p>✅ Recover only when the application can continue safely. Returning a fallback recommendation list is reasonable. Returning fake payment information is not.</p><p>✅ Log failures close to where they occur. Waiting until the final join() often loses valuable context.</p><p>✅ Don’t silently swallow exceptions. If a failure is important, either recover explicitly or allow it to propagate. Hidden failures are often harder to diagnose than visible ones.</p><p>✅ Design graceful degradation. In distributed systems, some dependencies will eventually fail. The goal isn’t to eliminate failures. It’s to ensure that one failed service doesn’t unnecessarily bring down the entire application.</p><p>At this point, our asynchronous pipelines can execute complex workflows, run independent tasks in parallel, and recover gracefully from failures. But there’s still one production problem we haven’t addressed.</p><p>Sometimes a service doesn’t fail…</p><p>it simply <strong>never responds</strong>. A request that hangs forever can be even more dangerous than one that fails immediately.</p><p>In the next section, we’ll learn how CompletableFuture lets us enforce time limits using orTimeout() and completeOnTimeout().</p><h3>Preventing Slow Services from Bringing Down Your Application</h3><p>So far, we’ve learned how to build asynchronous pipelines and recover from failures. But distributed systems have another kind of failure that’s often even more dangerous. Sometimes a service doesn’t fail. It simply <strong>never responds</strong>.</p><p>Imagine your Order Summary API calls three services.</p><ul><li>User Service ✅ 80 ms</li><li>Order Service ✅ 120 ms</li><li>Recommendation Service ❌ Still waiting…</li></ul><p>What should your application do? Wait forever?</p><p>Unfortunately, that’s exactly what happens if you don’t configure a timeout.</p><p>Your thread isn’t blocked, thanks to CompletableFuture, but your <strong>pipeline never completes</strong> because one stage is still waiting for a response.</p><p>Meanwhile:</p><ul><li>Memory remains occupied.</li><li>Connection pools stay busy.</li><li>Other requests begin piling up.</li><li>Response times increase across the system.</li></ul><p>One slow dependency can eventually affect the entire application. This is why every external dependency should have a timeout.</p><h3>orTimeout() — Fail if It Takes Too Long</h3><p>Suppose we’re calling a recommendation service.</p><pre>CompletableFuture&lt;List&lt;Product&gt;&gt; recommendations =<br>        CompletableFuture.supplyAsync(<br>                () -&gt; fetchRecommendations(userId),<br>                ioPool<br>        );</pre><p>Normally, this future completes whenever the service responds. But we may not be willing to wait indefinitely.</p><pre>CompletableFuture&lt;List&lt;Product&gt;&gt; recommendations =<br>        CompletableFuture<br>                .supplyAsync(<br>                        () -&gt; fetchRecommendations(userId),<br>                        ioPool<br>                )<br>                .orTimeout(3, TimeUnit.SECONDS);</pre><p>Now the behavior changes. If the service completes within three seconds, the pipeline continues normally. If not, the future completes exceptionally with a TimeoutException.</p><pre>Recommendation Service<br>↓<br><br>Still Waiting...<br>↓<br><br>3 Seconds<br>↓<br><br>TimeoutException</pre><p>Notice something important. orTimeout() <strong>doesn&#39;t make the service faster. </strong>It simply tells your application,</p><blockquote><em>“I’ve waited long enough. Continue by treating this as a failure.”</em></blockquote><p>That failure can then be handled using the same mechanisms we learned earlier.</p><pre>CompletableFuture&lt;List&lt;Product&gt;&gt; recommendations =<br>        CompletableFuture<br>                .supplyAsync(<br>                        () -&gt; fetchRecommendations(userId),<br>                        ioPool<br>                )<br>                .orTimeout(3, TimeUnit.SECONDS)<br>                .exceptionally(ex -&gt; Collections.emptyList());</pre><p>Instead of failing the entire request, we simply return no recommendations. The customer still receives the page. Only one feature is missing. This is an example of <strong>graceful degradation</strong>.</p><h3>completeOnTimeout() — Continue with a Default Value</h3><p>Sometimes a timeout isn’t really an error. Perhaps recommendations are optional. If they aren’t available quickly enough, we’d rather continue using a default value. That’s exactly what completeOnTimeout() does.</p><pre>CompletableFuture&lt;List&lt;Product&gt;&gt; recommendations =<br>        CompletableFuture<br>                .supplyAsync(<br>                        () -&gt; fetchRecommendations(userId),<br>                        ioPool<br>                )<br>                .completeOnTimeout(<br>                        Collections.emptyList(),<br>                        3,<br>                        TimeUnit.SECONDS<br>                );</pre><p>Now something different happens. If the recommendation service responds within three seconds, its result is used. Otherwise, the future completes successfully with an empty list. No exception is thrown. The rest of the pipeline doesn’t even know a timeout occurred.</p><pre>Recommendation Service<br>↓<br>No Response<br>↓<br>3 Seconds<br>↓<br>[]<br>↓<br>Pipeline Continues</pre><p>This is particularly useful for features that improve the user experience but aren’t essential to fulfilling the request.</p><p>Examples include:</p><ul><li>Product recommendations</li><li>Related articles</li><li>Recently viewed items</li><li>Promotional banners</li><li>Personalized advertisements</li></ul><p>The application remains responsive even when these services are unavailable.</p><h3>orTimeout() vs completeOnTimeout()</h3><p>At first glance, both methods seem similar. The difference lies in what happens after the timeout.</p><p>If you want to…UseTreat the timeout as a failureorTimeout()Continue with a default valuecompleteOnTimeout()</p><p>A simple way to remember them is:</p><ul><li><strong>orTimeout() says, &quot;This operation failed.&quot;</strong></li><li><strong>completeOnTimeout() says, &quot;Pretend this result arrived.&quot;</strong></li></ul><h3>Which One Should You Choose?</h3><p>There’s no universal answer. It depends on how important the operation is. Suppose your application is processing a payment. If the payment service doesn’t respond, using a default value would be disastrous. The request should fail. In that case, orTimeout() is the correct choice. Now consider a recommendation engine.</p><p>Customers can still purchase products even if recommendations aren’t available. Returning an empty list is perfectly acceptable.</p><p>Here,</p><p>completeOnTimeout() provides a much better user experience. The key principle is simple. <strong>Critical operations should fail fast. Optional operations should degrade gracefully.</strong></p><h3>A Production Best Practice</h3><p>One of the most common mistakes in asynchronous systems is forgetting to configure timeouts altogether. An exception is visible. A hanging request often isn’t. Until one day,</p><p>your thread pools, connection pools, or HTTP clients become exhausted because hundreds of requests are waiting for services that never responded. This is why mature backend systems almost always configure:</p><ul><li>Connection timeout</li><li>Read timeout</li><li>Retry policy</li><li>Circuit breaker</li><li>CompletableFuture timeout</li></ul><p>These mechanisms work together to keep the system responsive, even when some dependencies are slow or unavailable.</p><p>At this point, we’ve covered almost everything needed to build robust asynchronous workflows. There’s one final concept that often confuses developers. Sometimes the next stage runs on the same worker thread. Sometimes it runs on an entirely different one.</p><p>Why?</p><p>The answer lies in the difference between methods like thenApply() and thenApplyAsync(). Understanding that distinction will help you avoid unnecessary thread switches and build more efficient asynchronous pipelines.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e2219214f4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Concurrency & Async: The Complete Picture]]></title>
            <link>https://medium.com/@rajatraghav7797/java-concurrency-async-the-complete-picture-0a9e0a77bedf?source=rss-d50c9c063b6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a9e0a77bedf</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Rajat Kumar]]></dc:creator>
            <pubDate>Fri, 07 Aug 2026 17:49:33 GMT</pubDate>
            <atom:updated>2026-08-07T17:49:33.168Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 4 — Thread Pools &amp; Executors: Managing Threads at Scale</h3><p><em>Part of the series: Java Concurrency &amp; Async — The Complete Picture</em></p><blockquote><em>Part 3 [</em><a href="https://medium.com/@rajatraghav7797/java-concurrency-async-the-complete-picture-4aeac4c6ad85?sharedUserId=rajatraghav7797"><em>LINK</em></a><em>] gave you the tools to make shared state safe — synchronized, ReentrantLock, atomic classes. You know how to protect individual operations from concurrent interference.</em></blockquote><blockquote><em>But there’s a layer above that we haven’t touched: the threads themselves. How many should you create? Who creates them? What happens when more tasks arrive than threads can handle? Creating a new thread for every task is the most common concurrency mistake in production Java — and this part explains exactly why, and what to do instead.</em></blockquote><h3>The Problem With Creating Threads Directly</h3><p>In Part 1, you learned that a Thread is an OS-level resource — the JVM asks the operating system to create it, it gets its own stack memory, and it requires OS scheduler involvement every time it runs.</p><p>Creating a thread is not free. Typical cost:</p><ul><li><strong>Time:</strong> 0.5ms–1ms per thread creation on most JVMs</li><li><strong>Memory:</strong> 512KB–1MB of stack per thread (default stack size)</li><li><strong>OS resources:</strong> each thread is a kernel thread — the OS must track it, schedule it, switch to/from it</li></ul><p>Now consider a web server. At 1000 requests per second, creating one thread per request means:</p><pre>1000 threads/sec created × 1MB stack = 1GB RAM consumed per second<br>1000 threads/sec created × 1ms creation = 1 second of CPU just on thread creation</pre><p>Under any real load, the server spends more time creating and destroying threads than actually handling requests. Memory climbs until the process crashes. The OS scheduler thrashes trying to manage thousands of simultaneous threads.</p><p>This is the <strong>thread-per-task antipattern</strong> — and it kills services in production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uhvyBW-OGpb0_rDqv7CKrw.png" /></figure><p><em>Figure: Creating threads directly vs reusing them from a pool. Left: each task creates and destroys a thread. Right: tasks queue and execute on a fixed set of reused threads.</em></p><h3>The Thread Pool Idea</h3><p>The solution is conceptually simple: <strong>create threads once, reuse them many times.</strong></p><p>A thread pool maintains a set of worker threads that are always running, waiting for tasks. When a task arrives, it’s handed to an available worker. When the worker finishes, instead of dying, it goes back to waiting for the next task.</p><pre>Task queue: [Task A] [Task B] [Task C] [Task D] ...<br>                ↓<br>Thread pool: [Worker 1] [Worker 2] [Worker 3] [Worker 4]</pre><p>Worker 1 picks up Task A. Worker 2 picks up Task B. When Task A finishes, Worker 1 immediately picks up Task C. No thread creation. No thread destruction. The threads live for the lifetime of the pool.</p><p>Benefits:</p><ul><li>Thread creation cost paid once at startup</li><li>Memory is bounded — N threads, N megabytes of stack, predictable</li><li>The OS scheduler handles a manageable number of threads</li><li>Tasks that arrive faster than workers can handle them queue up rather than spawning unlimited threads</li></ul><h3>The Executor Framework</h3><p>Java’s answer to thread pools is the <strong>Executor framework</strong>, introduced in Java 5 via java.util.concurrent. At its core: a single interface.</p><pre>public interface Executor {<br>    void execute(Runnable command);<br>}</pre><p>You submit a task (Runnable). The executor decides how and when to run it. You don&#39;t create threads. You don&#39;t manage scheduling. You just say &quot;run this.&quot;</p><p>The richer interface is ExecutorService, which adds lifecycle management:</p><pre>public interface ExecutorService extends Executor {<br>    Future&lt;?&gt; submit(Runnable task);<br>    &lt;T&gt; Future&lt;T&gt; submit(Callable&lt;T&gt; task);<br>    void shutdown();            // stop accepting new tasks, finish existing ones<br>    List&lt;Runnable&gt; shutdownNow(); // stop immediately, return unfinished tasks<br>    boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException;<br>}</pre><p>You’ll use ExecutorService in almost all real code. Executor is mostly for passing around as a dependency.</p><h3>Creating Thread Pools: Executors Factory Methods</h3><p>The Executors class provides factory methods for common pool configurations. Know what each one actually does — the name alone isn&#39;t enough.</p><h3>Fixed thread pool</h3><pre>ExecutorService pool = Executors.newFixedThreadPool(4);</pre><p>Creates exactly 4 threads. All 4 live until the pool is shut down. Tasks queue in an <strong>unbounded queue</strong> (LinkedBlockingQueue with no capacity limit).</p><pre>// Example: process 100 tasks on 4 threads<br>ExecutorService pool = Executors.newFixedThreadPool(4);<br><br>for (int i = 0; i &lt; 100; i++) {<br>    final int taskId = i;<br>    pool.execute(() -&gt; {<br>        System.out.println(&quot;Task &quot; + taskId + &quot; running on &quot; + Thread.currentThread().getName());<br>        Thread.sleep(100); // simulate work<br>    });<br>}<br>pool.shutdown();<br>pool.awaitTermination(30, TimeUnit.SECONDS);<br>System.out.println(&quot;All tasks complete&quot;);</pre><p><strong>Output (interleaved):</strong></p><pre>Task 0 running on pool-1-thread-1<br>Task 1 running on pool-1-thread-2<br>Task 2 running on pool-1-thread-3<br>Task 3 running on pool-1-thread-4<br>Task 4 running on pool-1-thread-1   ← thread reused after Task 0 finished<br>Task 5 running on pool-1-thread-2<br>...<br>All tasks complete</pre><p><strong>The hidden danger:</strong> the unbounded queue. Under sustained overload, tasks keep queuing. The queue grows indefinitely. Eventually: OutOfMemoryError. A newFixedThreadPool in a high-traffic service with no queue limit is a memory leak waiting to happen.</p><h3>Cached thread pool</h3><pre>ExecutorService pool = Executors.newCachedThreadPool();</pre><p>Creates threads on demand. If all threads are busy and a new task arrives, creates a new thread. Idle threads are kept for 60 seconds, then terminated. No upper bound on thread count.</p><p>This sounds great. In production, it’s dangerous. Under a traffic spike, newCachedThreadPool will create thousands of threads to match the load — consuming gigabytes of stack memory, overwhelming the OS scheduler. It&#39;s the thread-per-task antipattern with a 60-second delay before threads die.</p><p><strong>Use </strong><strong>newCachedThreadPool only for:</strong> short-lived tasks with predictable, bounded concurrency. Almost never in a server application.</p><h3>Single thread executor</h3><pre>ExecutorService pool = Executors.newSingleThreadExecutor();</pre><p>One thread. Tasks execute sequentially in submission order. If the thread dies (uncaught exception), a replacement is created automatically.</p><p>Useful for: serializing access to a resource (database writes that must be ordered, file I/O), background task processing where order matters.</p><h3>Scheduled thread pool</h3><pre>ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);<br><br>// Run once after a delay<br>scheduler.schedule(() -&gt; System.out.println(&quot;Delayed task&quot;), 5, TimeUnit.SECONDS);<br>// Run repeatedly at fixed rate<br>scheduler.scheduleAtFixedRate(<br>    () -&gt; System.out.println(&quot;Heartbeat&quot;),<br>    0,        // initial delay<br>    30,       // period<br>    TimeUnit.SECONDS<br>);<br>// Run repeatedly with fixed delay BETWEEN executions<br>scheduler.scheduleWithFixedDelay(<br>    () -&gt; System.out.println(&quot;Polling&quot;),<br>    0,        // initial delay<br>    10,       // delay after last execution completes<br>    TimeUnit.SECONDS<br>);</pre><p><strong>scheduleAtFixedRate vs </strong><strong>scheduleWithFixedDelay:</strong></p><pre>scheduleAtFixedRate (period = 30s):<br>  Task starts at t=0, runs for 5s<br>  Next start: t=30 (regardless of when the task finished)<br>  Next start: t=60<br>  → Good for: metrics collection, heartbeats (wall-clock regularity matters)<br><br>scheduleWithFixedDelay (delay = 10s):<br>  Task starts at t=0, runs for 5s, finishes at t=5<br>  Next start: t=15 (5s finish + 10s delay)<br>  Next start: varies based on task duration<br>  → Good for: polling tasks where you want &quot;10s rest between runs&quot; not &quot;run every 10s&quot;</pre><p>If a scheduleAtFixedRate task takes longer than the period, the next execution starts immediately after the current one finishes (they don&#39;t stack up concurrently).</p><h3>The Right Way: ThreadPoolExecutor Directly</h3><p>The factory methods are convenient but hide important parameters. In production, you should construct ThreadPoolExecutor directly so you control every parameter:</p><pre>ThreadPoolExecutor executor = new ThreadPoolExecutor(<br>    4,                              // corePoolSize<br>    8,                              // maximumPoolSize<br>    60L,                            // keepAliveTime<br>    TimeUnit.SECONDS,               // keepAliveTime unit<br>    new ArrayBlockingQueue&lt;&gt;(100),  // work queue (BOUNDED — critical)<br>    new ThreadFactory() { ... },    // optional: name your threads<br>    new ThreadPoolExecutor.CallerRunsPolicy()  // rejection handler<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rjj2TGZ8WAMDYTTLyFceOw.png" /></figure><p><em>Figure: How ThreadPoolExecutor parameters interact. Core threads always alive. Extra threads created up to max when queue is full. Tasks rejected when both max threads and queue are full.</em></p><h3>The six parameters explained</h3><p><strong>corePoolSize</strong> — threads always kept alive, even when idle. The pool starts here and stays here under normal load.</p><p><strong>maximumPoolSize</strong> — the ceiling on total threads. Only exceeded when the work queue is full. max &gt; core allows bursting.</p><p><strong>keepAliveTime</strong> — how long excess threads (above core) stay alive when idle before being terminated.</p><p><strong>workQueue</strong> — where tasks wait when all core threads are busy. The choice here matters enormously:</p><pre>// Unbounded — dangerous in production. Queue grows forever under load.<br>new LinkedBlockingQueue&lt;&gt;()<br><br>// Bounded - tasks rejected when queue is full. Predictable memory.<br>new ArrayBlockingQueue&lt;&gt;(100)<br>// No queue - task handed directly to a thread or rejected.<br>// Forces creation of new threads up to max immediately.<br>new SynchronousQueue&lt;&gt;()<br>// Priority queue - tasks with higher priority run first.<br>new PriorityBlockingQueue&lt;&gt;()</pre><p><strong>Always use a bounded queue in production.</strong> Unbounded queues turn thread pool exhaustion into memory exhaustion — slower, harder to detect, and harder to recover from.</p><p><strong>threadFactory</strong> — controls how threads are created. The most useful thing you can do with this is <strong>name your threads</strong>:</p><pre>ThreadFactory namedFactory = new ThreadFactory() {<br>    private final AtomicInteger count = new AtomicInteger(0);<br><br>   @Override<br>    public Thread newThread(Runnable r) {<br>        Thread t = new Thread(r);<br>        t.setName(&quot;shipment-worker-&quot; + count.incrementAndGet());<br>        t.setDaemon(false);<br>        return t;<br>    }<br>};</pre><p>Named threads make thread dumps readable. “shipment-worker-3 is waiting on database lock” is infinitely more useful than “pool-1-thread-3 is waiting on database lock.”</p><p><strong>rejectionHandler</strong> — what happens when the queue is full AND all max threads are busy. Four built-in policies:</p><pre>AbortPolicy (default):<br>  Throws RejectedExecutionException<br>  → Task is lost. Caller must handle the exception.<br>  → Good when you can retry or fail fast.<br><br>CallerRunsPolicy:<br>  The submitting thread runs the task itself<br>  → Naturally slows down task submission when pool is overwhelmed<br>  → Good for batch processing where some slowdown is acceptable<br><br>DiscardPolicy:<br>  Silently drops the task<br>  → Task is lost, no exception<br>  → Rarely correct in production (silent data loss)<br><br>DiscardOldestPolicy:<br>  Drops the oldest waiting task, tries to submit the new one<br>  → Keeps queue fresh at the cost of losing old work<br>  → Use only when newest data is more valuable than oldest</pre><p>For most production services: CallerRunsPolicy or AbortPolicy with proper exception handling. DiscardPolicy is almost never correct.</p><h3>How the Pool Actually Decides What to Do</h3><p>The decision logic when a task arrives:</p><pre>Task submitted<br>      ↓<br>Are active threads &lt; corePoolSize?<br>  YES → Create new thread to run task immediately<br>  NO  ↓<br>Is the work queue full?<br>  NO  → Add task to queue (existing core threads will pick it up)<br>  YES ↓<br>Are active threads &lt; maximumPoolSize?<br>  YES → Create new thread (above core, up to max) to run task<br>  NO  ↓<br>Apply rejection handler</pre><p>This is counterintuitive: <strong>tasks queue before new threads are created above core size.</strong> The pool doesn’t rush to use all available thread capacity — it queues first. Only when the queue is full does it create additional threads up to max. Only when max threads AND the queue are both full does it reject.</p><p>This matters for sizing: if you want the pool to burst to max threads under load, you need a small or zero-capacity queue (SynchronousQueue). If you want to buffer tasks and use a stable thread count, use a large bounded queue.</p><h3>Submitting Tasks and Getting Results</h3><p>Two ways to submit work:</p><h3>execute() — fire and forget</h3><pre>executor.execute(() -&gt; sendEmail(user));<br>// Returns immediately. No way to know if/when task completed. No return value.</pre><p>Use when: you don’t need the result and don’t need to know when it finished.</p><h3>submit() — returns a Future</h3><pre>Future&lt;String&gt; future = executor.submit(() -&gt; {<br>    return fetchDataFromDatabase(userId);  // returns a value<br>});<br><br>// ... do other work ...<br>String result = future.get();  // blocks until task completes, returns value<br>// Or:<br>String result = future.get(5, TimeUnit.SECONDS);  // wait at most 5 seconds</pre><p>Future&lt;T&gt; represents a result that doesn&#39;t exist yet. .get() blocks the calling thread until the task finishes. .get(timeout) waits up to the timeout and throws TimeoutException if the task isn&#39;t done.</p><pre>// Checking status without blocking<br>if (future.isDone()) {<br>    result = future.get();  // won&#39;t block — already done<br>}<br><br>// Cancelling a task<br>future.cancel(true);  // true = interrupt the thread if already running</pre><p><strong>Future limitations:</strong></p><ul><li>.get() throws checked exceptions (ExecutionException, InterruptedException) — verbose to handle</li><li>No way to attach callbacks (“do X when this completes”)</li><li>Can’t chain futures (“do A, then B with A’s result, then C”)</li><li>Can’t combine multiple futures (“wait for all three to finish”)</li></ul><p>These limitations are exactly what CompletableFuture solves — but that&#39;s Part 5.</p><h3>Submitting Many Tasks: invokeAll and invokeAny</h3><pre>List&lt;Callable&lt;String&gt;&gt; tasks = List.of(<br>    () -&gt; fetchFromServiceA(),<br>    () -&gt; fetchFromServiceB(),<br>    () -&gt; fetchFromServiceC()<br>);<br><br>// Wait for ALL to finish, get all results<br>List&lt;Future&lt;String&gt;&gt; futures = executor.invokeAll(tasks);<br>for (Future&lt;String&gt; f : futures) {<br>    System.out.println(f.get());<br>}<br><br>// Return as soon as ANY ONE finishes (cancel the rest)<br>String fastest = executor.invokeAny(tasks);<br>System.out.println(&quot;Fastest result: &quot; + fastest);</pre><p>invokeAll blocks until every task completes. invokeAny blocks until at least one completes successfully (and cancels the rest). Use invokeAny for the <strong>hedged request</strong> pattern: send the same request to multiple replicas, use whichever responds first.</p><h3>Shutdown — The Part Everyone Gets Wrong</h3><p>An ExecutorService holds live threads. If you don&#39;t shut it down, those threads keep running even after main() returns — preventing the JVM from exiting (unless threads are daemon threads).</p><pre>// WRONG: pool never shut down → JVM hangs on exit<br>ExecutorService pool = Executors.newFixedThreadPool(4);<br>pool.execute(someTask);<br>// ... program ends but JVM doesn&#39;t exit<br><br>// CORRECT: graceful shutdown<br>pool.shutdown();  // stop accepting new tasks<br>pool.awaitTermination(30, TimeUnit.SECONDS);  // wait up to 30s for running tasks to finish<br><br><br>// CORRECT: forceful shutdown (for emergency or timeout)<br>pool.shutdownNow();  // interrupt running tasks, return queued ones</pre><p>The graceful shutdown pattern for Spring Boot services:</p><pre>@PreDestroy<br>public void shutdown() {<br>    log.info(&quot;Shutting down executor...&quot;);<br>    executor.shutdown();<br>    try {<br>        if (!executor.awaitTermination(30, TimeUnit.SECONDS)) {<br>            log.warn(&quot;Executor didn&#39;t terminate gracefully, forcing shutdown&quot;);<br>            executor.shutdownNow();<br>        }<br>    } catch (InterruptedException e) {<br>        executor.shutdownNow();<br>        Thread.currentThread().interrupt();<br>    }<br>}</pre><h3>Sizing Thread Pools — The Formula and the Reasoning</h3><p>How many threads should your pool have? The common mistake: “more threads = more throughput.” This is wrong above a certain point — and that point is often much lower than engineers assume.</p><p>The formula from Brian Goetz’s “Java Concurrency in Practice”:</p><pre>N_threads = N_cpu × U_cpu × (1 + W/C)<br><br>Where:<br>  N_cpu = number of CPU cores (Runtime.getRuntime().availableProcessors())<br>  U_cpu = target CPU utilization (0.0 to 1.0)<br>  W/C   = ratio of wait time to compute time</pre><p><strong>For CPU-bound tasks</strong> (image processing, cryptography, in-memory computation):</p><pre>W/C ≈ 0  (almost no waiting)<br>N_threads = N_cpu × 1.0 × (1 + 0) = N_cpu</pre><p>One thread per core. Adding more threads causes context switching overhead — they can’t run faster because CPU is the bottleneck.</p><p><strong>For I/O-bound tasks</strong> (database queries, HTTP calls, file reads):</p><pre>W/C ≈ 9  (waiting 90% of time, computing 10%)<br>N = 4 cores × 1.0 × (1 + 9) = 40 threads</pre><p>Many more threads than cores, because each thread spends most of its time blocked waiting for I/O, freeing the CPU for other threads. This is why web servers can handle hundreds of concurrent requests with far fewer CPU cores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*foHPGJ85hzO-vjutbrV4fQ.png" /></figure><p><em>Figure: CPU-bound tasks benefit from N_cpu threads. IO-bound tasks can use many more threads because threads spend most of their time waiting, not using CPU.</em></p><p><strong>In practice:</strong> measure, don’t calculate. The formula gives you a starting point. Profile your actual workload:</p><pre>// Expose pool stats via Micrometer (Spring Boot Actuator picks these up)<br>ThreadPoolExecutor pool = ...;<br><br>Gauge.builder(&quot;executor.pool.size&quot;, pool, ThreadPoolExecutor::getPoolSize)<br>     .register(meterRegistry);<br>Gauge.builder(&quot;executor.active.threads&quot;, pool, ThreadPoolExecutor::getActiveCount)<br>     .register(meterRegistry);<br>Gauge.builder(&quot;executor.queue.size&quot;, pool, p -&gt; p.getQueue().size())<br>     .register(meterRegistry);</pre><p>If queue.size is consistently &gt; 0, your pool is undersized or tasks are too slow. If active.threads is consistently much less than pool size, you may be oversized (wasting memory).</p><h3>Spring Boot Integration — @Async and TaskExecutor</h3><p>Spring Boot wraps all of this in @Async and auto-configured executors.</p><h3>Enabling async</h3><pre>@SpringBootApplication<br>@EnableAsync<br>public class Application { ... }</pre><h3>Configuring the executor</h3><pre>@Configuration<br>@EnableAsync<br>public class AsyncConfig implements AsyncConfigurer {<br><br>    @Override<br>    public Executor getAsyncExecutor() {<br>        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();<br>        executor.setCorePoolSize(4);<br>        executor.setMaxPoolSize(8);<br>        executor.setQueueCapacity(100);          // bounded queue<br>        executor.setThreadNamePrefix(&quot;async-&quot;);  // named threads<br>        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());<br>        executor.initialize();<br>        return executor;<br>    }<br>    @Override<br>    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {<br>        return (ex, method, params) -&gt;<br>            log.error(&quot;Uncaught exception in async method {}: {}&quot;, method.getName(), ex.getMessage(), ex);<br>    }<br>}</pre><h3>Using @Async</h3><pre>@Service<br>public class NotificationService {<br><br>    @Async<br>    public void sendEmail(String to, String subject, String body) {<br>        // runs on the async executor thread pool, not the caller&#39;s thread<br>        emailClient.send(to, subject, body);<br>        log.info(&quot;Email sent to {} on thread {}&quot;, to, Thread.currentThread().getName());<br>    }<br>    @Async<br>    public CompletableFuture&lt;String&gt; fetchReport(Long reportId) {<br>        // returns a future - caller can wait for result if needed<br>        String result = reportService.generate(reportId);<br>        return CompletableFuture.completedFuture(result);<br>    }<br>}</pre><pre>@RestController<br>public class OrderController {<br><br>    @PostMapping(&quot;/orders&quot;)<br>    public ResponseEntity&lt;Order&gt; placeOrder(@RequestBody OrderRequest request) {<br>        Order order = orderService.create(request);<br>        // Fire and forget - doesn&#39;t block the HTTP response<br>        notificationService.sendEmail(order.getUserEmail(), &quot;Order Confirmed&quot;, &quot;...&quot;);<br>        return ResponseEntity.ok(order);<br>    }<br>}</pre><h3>The @Async self-invocation trap</h3><p>This is the same proxy issue from Spring Boot internals (your Spring Boot series). @Async works through Spring AOP proxies — calling an @Async method from within the same class bypasses the proxy and runs synchronously on the caller&#39;s thread:</p><pre>@Service<br>public class OrderService {<br><br>    @Async<br>    public void processAsync() { ... }  // should run async<br>    public void trigger() {<br>        processAsync();  // WRONG: calls this.processAsync(), bypasses proxy<br>                         // runs synchronously on caller&#39;s thread<br>    }<br>}<br><br>// Fix: inject the service into itself, or extract to a separate bean<br>@Service<br>public class OrderService {<br>    @Autowired<br>    private OrderService self;  // Spring injects the proxy, not &#39;this&#39;<br>    public void trigger() {<br>        self.processAsync();  // goes through proxy → runs async correctly<br>    }<br>}</pre><h3>Common Mistakes in Production</h3><p><strong>Mistake 1: Using Executors.newFixedThreadPool without knowing the queue is unbounded</strong></p><p>Under sustained load, tasks pile up in the unbounded queue. Memory grows until OutOfMemoryError. The fix: new ArrayBlockingQueue&lt;&gt;(capacity) with a rejection handler.</p><p><strong>Mistake 2: Not naming threads</strong></p><p>Thread dumps show “pool-1-thread-3 waiting on…” — useless. Name your threads in the ThreadFactory. &quot;shipment-processor-3 waiting on...&quot; tells you immediately which pool is stuck.</p><p><strong>Mistake 3: Catching InterruptedException and not restoring the interrupt flag</strong></p><pre>// Wrong<br>try {<br>    Thread.sleep(1000);<br>} catch (InterruptedException e) {<br>    // swallowed — thread doesn&#39;t know it was interrupted<br>}<br><br>// Correct<br>try {<br>    Thread.sleep(1000);<br>} catch (InterruptedException e) {<br>    Thread.currentThread().interrupt();  // restore flag<br>    return;  // exit cleanly<br>}</pre><p><strong>Mistake 4: Sharing mutable state between tasks submitted to the same pool</strong></p><p>Tasks running on different pool threads share the heap — all the race conditions from Part 2 and Part 3 still apply. The thread pool doesn’t give you any synchronization between tasks automatically.</p><p><strong>Mistake 5: Not shutting down the pool</strong></p><p>Pools with non-daemon threads prevent JVM exit. Always shutdown() in a @PreDestroy or shutdown hook.</p><h3>Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2eRhKrf-tP68f2SYgDDJMQ.png" /></figure><p><em>Next in the series: Part 5 — CompletableFuture. </em><em>Future&lt;T&gt; from this part works but is limited — blocking </em><em>.get(), no callbacks, no chaining. </em><em>CompletableFuture fixes all of that, enabling non-blocking async pipelines. You&#39;ll also see how to combine multiple async operations — fan-out, fan-in, timeouts — which is where async Java becomes genuinely powerful.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a9e0a77bedf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Concurrency & Async: The Complete Picture]]></title>
            <link>https://medium.com/@rajatraghav7797/java-concurrency-async-the-complete-picture-4aeac4c6ad85?source=rss-d50c9c063b6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4aeac4c6ad85</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Rajat Kumar]]></dc:creator>
            <pubDate>Thu, 06 Aug 2026 07:37:19 GMT</pubDate>
            <atom:updated>2026-08-06T07:40:02.672Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 3 — Locks &amp; Atomicity: Making Shared State Safe</h4><h4><em>Part of the series: Java Concurrency &amp; Async — The Complete Picture</em></h4><blockquote><em>Part 2 [</em><a href="https://medium.com/@rajatraghav7797/part-2-java-concurrency-async-the-complete-picture-1b89604945e7?sharedUserId=rajatraghav7797"><strong><em>LINK</em></strong></a><em>] showed you why shared mutable state is dangerous even without interleaving — CPU caches can hide writes entirely. </em><em>volatile fixes visibility: writes are always flushed, reads always go to main memory.</em></blockquote><blockquote><em>But </em><em>volatile isn&#39;t enough. Some operations aren&#39;t a single read or write — they&#39;re multiple steps that need to complete as one indivisible unit. This part is about that problem, and the tools Java gives you to solve it.</em></blockquote><h3>The Problem volatile Can’t Solve</h3><p>Here’s the code that broke in Part 2:</p><pre>private volatile int counter = 0;<br><br>public void increment() {<br>    counter++;  // looks like one operation. It isn&#39;t.<br>}</pre><p>volatile makes the value always visible. But counter++ isn&#39;t one operation — it&#39;s three:</p><pre>READ   the current value of counter into a CPU register<br>ADD    1 to that register<br>WRITE  the register back to counter</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jTFTRHTYP1GPh8685KBZhQ.png" /></figure><p>Between the READ and the WRITE, another thread can sneak in and read the same value, compute its own increment, and write back — overwriting your result. Both increments happened, but only one is reflected in the final value. This is called a <strong>race condition</strong>.</p><p>The formal name for what’s missing: <strong>atomicity</strong> — the property that an operation completes as one indivisible unit, with no other thread able to observe an intermediate state.</p><p>volatile gives you visibility. Atomicity is a different problem entirely.</p><h3>Two Concepts, One Mental Model</h3><p>Before the tools, get this distinction firmly in your head:</p><p>Property The problem it solves The question it answers <strong>Visibility</strong> CPU caches hide writes from other threads “Can Thread B see what Thread A wrote?” <strong>Atomicity</strong> Multi-step operations can be interrupted mid-way “Can Thread B see Thread A halfway through an operation?”</p><p>volatile solves visibility. The tools in this part solve atomicity (and also provide visibility as part of the deal).</p><h3>Tool 1: synchronized — The Simplest Lock</h3><p>Every Java object — literally every object, from a String to your own Counter class — has a built-in lock called a <strong>monitor</strong> (or intrinsic lock). The synchronized keyword acquires this lock.</p><pre>public class Counter {<br>    private int count = 0;<br><br>    public synchronized void increment() {<br>        count++;  // only one thread executes this at a time<br>    }<br><br>    public synchronized int getCount() {<br>        return count;<br>    }<br>}</pre><p>When Thread A calls increment(), it acquires the monitor lock on this. Any other thread that tries to call increment() or getCount() — any synchronized method on the same object — immediately blocks. It waits until Thread A exits the method and releases the lock.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SwdTLCf9VX29he4zB8yjaw.png" /></figure><h3>What synchronized guarantees</h3><p><strong>Mutual exclusion:</strong> only one thread executes any synchronized block on the same object at a time. This makes the three-step counter++ indivisible from the perspective of other threads — no thread can see the in-between state.</p><p><strong>Visibility:</strong> when a thread releases a synchronized lock, all its writes are flushed to main memory. When a thread acquires the lock, it reads fresh values. You get visibility for free — no separate volatile needed.</p><p><strong>Happens-before:</strong> everything inside the block happens-before everything the next thread sees after it acquires the same lock. This is the formal guarantee that makes synchronized correct.</p><h3>Synchronized on a block, not just a method</h3><p>You don’t have to synchronize the entire method. You can synchronize on any object, for just the critical section:</p><pre>public class Counter {<br>    private int count = 0;<br>    private final Object lock = new Object();  // dedicated lock object<br>    <br>    public void increment() {<br>        // do non-critical work here (no lock held) ...<br>        synchronized (lock) {<br>            count++;  // only this tiny section is locked<br>        }<br>        // do more non-critical work here ...<br>    }<br>}</pre><p>Smaller synchronized blocks = less time the lock is held = less time other threads spend waiting. Keep synchronized blocks as small as possible.</p><h3>The most common mistake: synchronizing on different objects</h3><pre>// WRONG — two different lock objects<br>public class BrokenCounter {<br>    private int count = 0;<br><br>    public void increment() {<br>        synchronized (new Object()) {  // new object every time = no mutual exclusion!<br>            count++;<br>        }<br>    }<br>}</pre><p>For synchronized to provide mutual exclusion, every thread must synchronize on the <strong>same</strong> object. Two threads synchronizing on two different objects provide zero protection from each other — they acquire different locks and proceed in parallel.</p><h3>A real runnable example</h3><pre>public class SynchronizedDemo {<br>    private int count = 0;<br>    <br>    public synchronized void increment() {<br>        count++;<br>    }<br>   <br>    public synchronized int getCount() {<br>        return count;<br>    }<br>    <br>    public static void main(String[] args) throws InterruptedException {<br>        SynchronizedDemo counter = new SynchronizedDemo();<br>        Thread t1 = new Thread(() -&gt; {<br>            for (int i = 0; i &lt; 10_000; i++) counter.increment();<br>        });<br>        Thread t2 = new Thread(() -&gt; {<br>            for (int i = 0; i &lt; 10_000; i++) counter.increment();<br>        });<br>        t1.start();<br>        t2.start();<br>        t1.join();<br>        t2.join();<br>        System.out.println(&quot;Final count: &quot; + counter.getCount());<br>        // Always prints: Final count: 20000<br>        // Without synchronized: might print 14237, 18903, anything less than 20000<br>    }<br>}</pre><p>Run this without synchronized and you&#39;ll get a different (wrong) number almost every time. With synchronized, you get exactly 20,000 every time.</p><h3>Tool 2: ReentrantLock — When synchronized Isn’t Flexible Enough</h3><p>synchronized is simple and safe. But it has real limitations in production scenarios. ReentrantLock from java.util.concurrent.locks gives you everything synchronized does, plus more control.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dI2RZQOBAQxr81i4KzmgPw.png" /></figure><h3>The limitations of synchronized</h3><p><strong>No way to try without blocking.</strong> With synchronized, if the lock is held, your thread blocks — period. You can&#39;t say &quot;try to acquire, and if it&#39;s busy, do something else.&quot;</p><p><strong>No timeout.</strong> You can’t say “wait at most 2 seconds for the lock, then give up.” A thread waiting on a synchronized block will wait until the lock is released or the JVM shuts down.</p><p><strong>No interruptibility.</strong> Calling Thread.interrupt() on a thread waiting on a synchronized block has no effect. It continues waiting.</p><p><strong>No fairness.</strong> When multiple threads are waiting for a lock, synchronized picks the next owner arbitrarily. A thread could theoretically wait indefinitely (starvation) if it keeps getting skipped.</p><h3>ReentrantLock in practice</h3><pre>import java.util.concurrent.locks.ReentrantLock;<br>import java.util.concurrent.TimeUnit;<br><br>public class BetterCounter {<br>    private int count = 0;<br>    private final ReentrantLock lock = new ReentrantLock();<br>    // Basic usage - same as synchronized<br>    public void increment() {<br>        lock.lock();<br>        try {<br>            count++;<br>        } finally {<br>            lock.unlock();  // ALWAYS in finally - never forget this<br>        }<br>    }<br>    // Try without blocking<br>    public boolean tryIncrement() {<br>        if (lock.tryLock()) {<br>            try {<br>                count++;<br>                return true;<br>            } finally {<br>                lock.unlock();<br>            }<br>        }<br>        return false;  // lock was busy - did something else instead<br>    }<br>    // Try with timeout<br>    public boolean tryIncrementWithTimeout() throws InterruptedException {<br>        if (lock.tryLock(2, TimeUnit.SECONDS)) {<br>            try {<br>                count++;<br>                return true;<br>            } finally {<br>                lock.unlock();<br>            }<br>        }<br>        return false;  // gave up after 2 seconds<br>    }<br>}</pre><p><strong>Critical rule:</strong> always call lock.unlock() in a finally block. If you call lock.lock() and then throw an exception before calling unlock(), the lock is held forever — every thread waiting on it is stuck permanently. With synchronized, the JVM handles release automatically. With ReentrantLock, you&#39;re responsible.</p><h3>Fair lock — preventing starvation</h3><pre>// True = fair mode: longest-waiting thread gets lock next<br>private final ReentrantLock fairLock = new ReentrantLock(true);</pre><p>Fair locks prevent any thread from waiting indefinitely. The cost: lower throughput. Under high contention, a fair lock is slower because it enforces strict ordering. Use fair locks when you have a known starvation problem — not by default.</p><h3>Why it’s called “Reentrant”</h3><p>Both synchronized and ReentrantLock are reentrant: a thread that already holds the lock can acquire it again without deadlocking itself.</p><pre>public synchronized void outer() {<br>    inner();  // calls another synchronized method — this thread already holds the lock<br>}<br><br>public synchronized void inner() {<br>    // works fine - same thread can re-enter<br>    System.out.println(&quot;inner&quot;);<br>}</pre><p>Without reentrancy, outer() calling inner() would deadlock — the thread would try to acquire a lock it already holds, then wait forever for itself. Java&#39;s locks keep a count of how many times the same thread acquired them and only fully release when the count reaches zero.</p><h3>Tool 3: Atomic Classes — Lock-Free Thread Safety</h3><p>For simple single-variable operations — counters, flags, references — you don’t need a lock at all. The java.util.concurrent.atomic package gives you thread-safe operations built directly on CPU hardware instructions.</p><h3>The hardware instruction underneath: Compare-And-Swap</h3><p>All atomic classes are built on <strong>Compare-And-Swap (CAS)</strong> — a single CPU instruction that does this:</p><pre>CAS(memory_address, expected_value, new_value):<br>  if value at address == expected_value:<br>    atomically replace with new_value<br>    return true<br>  else:<br>    return false (someone else changed it)</pre><p>This is one instruction at the CPU level — indivisible. No thread scheduling can interrupt it. No lock is needed because the hardware itself guarantees atomicity.</p><p>AtomicInteger.incrementAndGet() uses CAS in a loop:</p><pre>// What AtomicInteger.incrementAndGet() effectively does:<br>public int incrementAndGet() {<br>    while (true) {<br>        int current = get();       // read current value<br>        int next = current + 1;   // compute new value<br>        if (compareAndSet(current, next)) {  // CAS: only succeeds if nobody changed value since we read<br>            return next;          // we won the race<br>        }<br>        // CAS failed — someone else changed value between our read and CAS<br>        // loop and try again with fresh value<br>    }<br>}</pre><p>No lock acquired. No thread blocking. If two threads compete, one succeeds and the other loops — wastes a tiny bit of CPU but never blocks.</p><h3>AtomicInteger in practice</h3><pre>import java.util.concurrent.atomic.AtomicInteger;<br><br>public class AtomicCounter {<br>    private final AtomicInteger count = new AtomicInteger(0);<br>    public void increment() {<br>        count.incrementAndGet();  // thread-safe, no lock<br>    }<br>    public int getCount() {<br>        return count.get();<br>    }<br>    public static void main(String[] args) throws InterruptedException {<br>        AtomicCounter counter = new AtomicCounter();<br>        Thread t1 = new Thread(() -&gt; {<br>            for (int i = 0; i &lt; 10_000; i++) counter.increment();<br>        });<br>        Thread t2 = new Thread(() -&gt; {<br>            for (int i = 0; i &lt; 10_000; i++) counter.increment();<br>        });<br>        t1.start(); t2.start();<br>        t1.join();  t2.join();<br>        System.out.println(&quot;Final count: &quot; + counter.getCount());<br>        // Always prints: Final count: 20000<br>    }<br>}</pre><h3>When to use each</h3><pre>Single variable, simple operation (counter, flag, single reference swap):<br>  → AtomicInteger / AtomicLong / AtomicBoolean / AtomicReference<br>  → Lock-free, fast under low-moderate contention<br><br>High-throughput counter (metrics, event counting):<br>  → LongAdder (shards counter per CPU thread - eliminates CAS contention)<br>  → sum() to read; incrementAndGet() to update<br><br>Multiple variables that must change together:<br>  → synchronized or ReentrantLock<br>  → AtomicInteger cannot atomically protect two variables at once</pre><p>The last point is critical. Suppose you have a bank account with balance and lastTransactionAmount. Updating both atomically — ensuring no thread sees balance updated but lastTransactionAmount stale — requires a lock. Two separate AtomicIntegers can&#39;t guarantee that.</p><h3>Tool 4: ReadWriteLock — For Read-Heavy Workloads</h3><p>One specific scenario where synchronized and ReentrantLock are too aggressive: when reads vastly outnumber writes, and reads don&#39;t interfere with each other.</p><p>With synchronized, every reader blocks every other reader — even though two readers simultaneously is perfectly safe (they&#39;re both just reading, changing nothing).</p><p>ReadWriteLock separates the concerns:</p><pre>import java.util.concurrent.locks.ReadWriteLock;<br>import java.util.concurrent.locks.ReentrantReadWriteLock;<br><br>public class Cache {<br>    private final Map&lt;String, String&gt; data = new HashMap&lt;&gt;();<br>    private final ReadWriteLock rwLock = new ReentrantReadWriteLock();<br>    <br><br>    public String get(String key) {<br>        rwLock.readLock().lock();   // multiple threads can hold readLock simultaneously<br>        try {<br>            return data.get(key);<br>        } finally {<br>            rwLock.readLock().unlock();<br>        }<br>    }<br><br><br>    public void put(String key, String value) {<br>        rwLock.writeLock().lock();  // exclusive - blocks all readers and writers<br>        try {<br>            data.put(key, value);<br>        } finally {<br>            rwLock.writeLock().unlock();<br>        }<br>    }<br>}</pre><p>Rules: many threads can hold the read lock simultaneously (they don’t block each other). A write lock is exclusive — while a writer holds it, no reader or writer can enter. When there’s a writer waiting, new readers block (to prevent writer starvation).</p><p>Use ReadWriteLock when: reads are frequent (&gt;80% of operations), reads take meaningful time, and writes are infrequent. For simple counters or single-field updates, the overhead isn&#39;t worth it.</p><h3>Deadlock — The Silent Killer</h3><p>All locking introduces the possibility of deadlock. Understanding it — both how it happens and how to prevent it — is non-negotiable for anyone writing concurrent code.</p><h3>What deadlock is</h3><p>A deadlock occurs when two or more threads are each waiting for a lock that another thread holds — and none of them can proceed:</p><pre>// Thread 1                    // Thread 2<br>synchronized (lockA) {         synchronized (lockB) {<br>    // does some work              // does some work<br>    synchronized (lockB) {        synchronized (lockA) {<br>        // needs lockB                // needs lockA<br>        // BLOCKED — waiting          // BLOCKED — waiting<br>    }                             }<br>}                              }</pre><p>Thread 1 holds lockA, wants lockB. Thread 2 holds lockB, wants lockA. Neither can proceed. Neither releases. Both wait forever.</p><p>No exception is thrown. No timeout fires. Threads are simply suspended, silently. The JVM does not automatically detect or recover from deadlock. If this happens in production, affected functionality stops working until the process is restarted.</p><h3>Prevention Strategy 1: Consistent lock ordering (best)</h3><p>The simplest and most reliable prevention: <strong>always acquire locks in the same order, everywhere in your codebase.</strong></p><pre>// Both Thread 1 AND Thread 2 always do: lockA first, then lockB<br>synchronized (lockA) {<br>    synchronized (lockB) {<br>        // safe — no circular wait possible<br>    }<br>}</pre><p>If every thread acquires locks in the same order, circular wait is mathematically impossible. Thread 1 can’t hold lockB while waiting for lockA, because acquiring lockA always comes first.</p><h3>Prevention Strategy 2: tryLock with timeout</h3><pre>// Using ReentrantLock to avoid infinite wait<br>boolean acquiredA = false, acquiredB = false;<br>try {<br>    acquiredA = lockA.tryLock(1, TimeUnit.SECONDS);<br>    acquiredB = lockB.tryLock(1, TimeUnit.SECONDS);<br><br>    if (acquiredA &amp;&amp; acquiredB) {<br>        // do the work<br>    } else {<br>        // couldn&#39;t get both - release what we have and retry later<br>    }<br><br>} finally {<br>    if (acquiredB) lockB.unlock();<br>    if (acquiredA) lockA.unlock();<br>}</pre><p>If you can’t acquire both locks within the timeout, release everything and try again. This breaks the deadlock — one thread gives up, the other proceeds.</p><h3>Prevention Strategy 3: Minimize lock scope</h3><p>The fewer locks you hold simultaneously, and the shorter you hold them, the less opportunity for deadlock:</p><pre>// Bad: long lock scope, calling external methods while locked<br>synchronized (lock) {<br>    result = expensiveExternalCall();  // ← DO NOT do this while holding a lock<br>    updateState(result);<br>}<br><br>// Better: only lock what truly needs protection<br>String result = expensiveExternalCall();  // no lock held during expensive call<br>synchronized (lock) {<br>    updateState(result);  // lock only for the state update<br>}</pre><p>Never call external methods (other classes, network calls, file I/O) while holding a lock. You have no idea what locks those methods might try to acquire — and that’s exactly how deadlocks sneak into real codebases.</p><h3>Detecting deadlocks in production</h3><pre># Get the PID of your Java process<br>pgrep -f YourAppName<br><br># Take a thread dump - shows all threads and their lock status<br>jstack &lt;pid&gt;<br># Output includes sections like:<br># Found 1 deadlock.<br># &quot;Thread-1&quot;:<br>#   waiting to lock monitor 0x00007f... (object 0x..., a java.lang.Object)<br>#   which is held by &quot;Thread-0&quot;<br># &quot;Thread-0&quot;:<br>#   waiting to lock monitor 0x00007f... (object 0x..., a java.lang.Object)<br>#   which is held by &quot;Thread-1&quot;</pre><p>jstack is a free JDK tool with zero overhead — you can run it on production processes at any time without affecting performance.</p><h3>The Producer-Consumer Pattern — Locking in Practice</h3><p>The producer-consumer pattern is the canonical example of threads coordinating through a shared data structure. One or more threads produce data (orders, events, tasks), one or more threads consume it. The buffer between them is the coordination point.</p><pre>import java.util.LinkedList;<br>import java.util.Queue;<br><br>public class ProducerConsumer {<br>    private final Queue&lt;Integer&gt; buffer = new LinkedList&lt;&gt;();<br>    private final int capacity;<br>    private final Object lock = new Object();<br>    public ProducerConsumer(int capacity) {<br>        this.capacity = capacity;<br>    }<br>    // Producer: add item to buffer, wait if full<br>    public void produce(int item) throws InterruptedException {<br>        synchronized (lock) {<br>            while (buffer.size() == capacity) {<br>                lock.wait();  // buffer full - release lock and wait<br>            }<br>            buffer.add(item);<br>            System.out.println(&quot;Produced: &quot; + item + &quot; | Buffer size: &quot; + buffer.size());<br>            lock.notifyAll();  // wake up any waiting consumers<br>        }<br>    }<br>    // Consumer: take item from buffer, wait if empty<br>    public int consume() throws InterruptedException {<br>        synchronized (lock) {<br>            while (buffer.isEmpty()) {<br>                lock.wait();  // buffer empty - release lock and wait<br>            }<br>            int item = buffer.poll();<br>            System.out.println(&quot;Consumed: &quot; + item + &quot; | Buffer size: &quot; + buffer.size());<br>            lock.notifyAll();  // wake up any waiting producers<br>            return item;<br>        }<br>    }<br>    public static void main(String[] args) {<br>        ProducerConsumer pc = new ProducerConsumer(5);<br>        Thread producer = new Thread(() -&gt; {<br>            try {<br>                for (int i = 0; i &lt; 10; i++) {<br>                    pc.produce(i);<br>                    Thread.sleep(100);<br>                }<br>            } catch (InterruptedException e) {<br>                Thread.currentThread().interrupt();<br>            }<br>        });<br>        Thread consumer = new Thread(() -&gt; {<br>            try {<br>                for (int i = 0; i &lt; 10; i++) {<br>                    pc.consume();<br>                    Thread.sleep(200);  // consumer is slower than producer<br>                }<br>            } catch (InterruptedException e) {<br>                Thread.currentThread().interrupt();<br>            }<br>        });<br>        producer.start();<br>        consumer.start();<br>    }<br>}</pre><p><strong>Sample output:</strong></p><pre>Produced: 0 | Buffer size: 1<br>Produced: 1 | Buffer size: 2<br>Consumed: 0 | Buffer size: 1<br>Produced: 2 | Buffer size: 2<br>Produced: 3 | Buffer size: 3<br>Consumed: 1 | Buffer size: 2<br>Produced: 4 | Buffer size: 3<br>Produced: 5 | Buffer size: 4<br>Consumed: 2 | Buffer size: 3<br>...</pre><h3>The critical details in this code</h3><p><strong>wait() inside a </strong><strong>while loop, not </strong><strong>if:</strong></p><pre>// WRONG — if<br>if (buffer.isEmpty()) {<br>    lock.wait();<br>}<br><br>// RIGHT - while<br>while (buffer.isEmpty()) {<br>    lock.wait();<br>}</pre><p>Why while? Because notifyAll() wakes up ALL waiting threads. Suppose 3 consumer threads are waiting for items. One item arrives. All 3 wake up. The first one takes the item. The other two check the condition again — the buffer is empty. Without the while, they proceed to buffer.poll() on an empty queue — NullPointerException. With while, they re-check and wait again. This is so important it has a name: <strong>spurious wakeup protection</strong>.</p><p><strong>wait() releases the lock:</strong></p><p>When a thread calls lock.wait(), it releases the monitor lock entirely — other threads can enter the synchronized block. When the thread is notified and re-awakened, it re-acquires the lock before proceeding. This is what allows producers and consumers to interleave correctly.</p><p><strong>notifyAll() vs </strong><strong>notify():</strong></p><p>notify() wakes one arbitrary waiting thread. notifyAll() wakes all of them. Use notifyAll() unless you have a specific reason for notify() and you&#39;re certain about which thread should wake up. With notify(), you risk waking a thread that can&#39;t proceed (e.g., waking a consumer when you&#39;re a producer who needs another producer to wake up).</p><h3>In production: use BlockingQueue instead</h3><p>The above is instructive for understanding wait()/notifyAll() mechanics. In real production code, use java.util.concurrent.BlockingQueue — it implements producer-consumer correctly and efficiently without you writing any locking:</p><pre>import java.util.concurrent.ArrayBlockingQueue;<br>import java.util.concurrent.BlockingQueue;<br><br>BlockingQueue&lt;Integer&gt; queue = new ArrayBlockingQueue&lt;&gt;(5);<br>// Producer<br>queue.put(item);    // blocks if full - automatically<br>// Consumer<br>int item = queue.take();  // blocks if empty - automatically</pre><p>BlockingQueue handles all the wait()/notifyAll() internally, correctly, and efficiently. Always prefer it over hand-rolled producer-consumer code.</p><h3>Choosing the Right Tool</h3><pre>What do you need?                           Use this<br>──────────────────────────────────────────────────────────────────<br>Counter, flag, single reference             AtomicInteger / AtomicBoolean / AtomicReference<br><br>High-throughput counter (metrics)           LongAdder<br><br>Multiple variables must change together     synchronized (simple case)<br><br>Need timeout / tryLock / interruptibility   ReentrantLock<br><br>Read-heavy, infrequent writes               ReadWriteLock<br><br>Producer-consumer coordination              BlockingQueue (or ReentrantLock + Condition)</pre><p>The progression: start with the simplest tool that solves your problem. Atomic classes → synchronized → ReentrantLock. Don’t reach for a complex tool when a simple one works — complexity is where bugs live.</p><h3>Common Mistakes — and How to Spot Them</h3><p><strong>Mistake 1: Synchronizing on a different object every call</strong></p><pre>// Bug: new Object() every time = different lock every time = no mutual exclusion<br>synchronized (new Object()) { ... }</pre><p><strong>Mistake 2: Not releasing ReentrantLock in finally</strong></p><pre>lock.lock();<br>doSomething();  // throws exception<br>lock.unlock();  // never reached → lock held forever<br>// Fix: always unlock in finally</pre><p><strong>Mistake 3: Calling wait() without owning the lock</strong></p><pre>// Bug: must be inside synchronized block to call wait()<br>lock.wait();  // throws IllegalMonitorStateException</pre><p><strong>Mistake 4: Using notify() when notifyAll() is needed</strong></p><pre>// Risky: wakes one arbitrary thread. If it&#39;s the wrong thread, nothing proceeds.<br>lock.notify();  // prefer notifyAll() unless you&#39;re certain</pre><p><strong>Mistake 5: Holding a lock while calling external code</strong></p><pre>synchronized (lock) {<br>    httpClient.post(url, data);  // external call — unknown locks, unknown latency<br>    // Risk: locks held during network call = contention + potential deadlock<br>}</pre><h3>Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ol3fjeHcO75hexn8io1vg.png" /></figure><p>The tools build on each other. synchronized is the foundation. ReentrantLock extends it with flexibility. Atomic classes bypass locks entirely using hardware. Each level trades simplicity for capability. Know when to move up — and when to stay at the simpler level.</p><p><em>Next in the series: Part 4 — Thread Pools &amp; Executors. You now know how to make individual operations thread-safe. Part 4 covers how to manage the threads themselves — how many to create, how to reuse them, what happens when they’re all busy, and the executor framework that makes this manageable.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4aeac4c6ad85" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 2: Java Concurrency & Async: The Complete Picture]]></title>
            <link>https://medium.com/@rajatraghav7797/part-2-java-concurrency-async-the-complete-picture-1b89604945e7?source=rss-d50c9c063b6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b89604945e7</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Rajat Kumar]]></dc:creator>
            <pubDate>Thu, 06 Aug 2026 07:34:34 GMT</pubDate>
            <atom:updated>2026-08-08T17:13:33.210Z</atom:updated>
            <content:encoded><![CDATA[<h4>The Java Memory Model &amp; Visibility</h4><blockquote><strong><em>The part almost every async article skips</em></strong></blockquote><h3>1. The Pain: Code That’s “Correct” and Still Wrong</h3><p>Here’s a shutdown flag — the kind of thing that shows up in almost every worker-thread implementation:</p><pre>public class Worker {<br>    private boolean running = true;<br><br>    public void start() {<br>        new Thread(() -&gt; {<br>            while (running) {<br>                doWork();<br>            }<br>            System.out.println(&quot;Stopped&quot;);<br>        }).start();<br>    }<br><br>    public void stop() {<br>        running = false;<br>    }<br>}</pre><p>Call stop() from the main thread. On your laptop, in a quick test, it stops. Ship the exact same code to a multi-core production server under load, and the worker thread can spin in that while (running) loop <strong>forever</strong> — even though running is unmistakably false in the thread that called stop().</p><p>Nothing here is a race condition in the usual sense — there’s no lost update, no two threads writing at once. The write happens. It’s just that the reading thread may never <em>see</em> it. That’s a different, quieter kind of bug, and it’s the one most Java developers have never had explained to them, because it doesn’t show up in Runnable/Executor/CompletableFuture tutorials at all. It lives one layer underneath all of that.</p><h3>2. Why the Write Can Go Missing</h3><p>Modern CPUs don’t read and write straight to main memory for every instruction — that would be far too slow. Each core keeps its own cache, and a thread pinned to one core can happily read and write running from <em>its own core&#39;s cache</em> for a long time before that value gets flushed back to main memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uYNB6b3YgNwM_MoNLQnF0Q.png" /></figure><p>The writer thread’s running = false lands in Core 1&#39;s cache. The reader thread, spinning on Core 2, keeps rereading its own cached copy — true — because nothing has told it that copy is stale. Two things conspire to make this worse than it sounds:</p><ul><li><strong>The JIT compiler is allowed to optimize the loop.</strong> If it can prove running isn&#39;t modified <em>within</em> the loop body, it&#39;s legally allowed to hoist the read out entirely and check it once — turning while (running) { doWork(); } into an effectively infinite loop, compiler-optimized and everything.</li><li><strong>This is legal, not a bug in the JVM.</strong> The Java Language Specification doesn’t require a plain field read to see another thread’s plain field write in any particular timeframe. Nothing is broken — you just never asked for the guarantee you’re relying on.</li></ul><p>This is the <strong>visibility problem</strong>, and it’s distinct from the <strong>atomicity problem</strong> most people learn first (two threads incrementing a counter and losing an update). Visibility is about <em>whether a write is ever seen at all</em>; atomicity is about <em>whether a read-modify-write sequence is safe from interleaving</em>. volatile solves visibility. It does <strong>not</strong> solve atomicity — that distinction is where a lot of volatile misuse comes from, and we&#39;ll come back to it at the end.</p><h3>3. The Fix: volatile</h3><pre>public class Worker {<br>    private volatile boolean running = true;<br>    // ...<br>}</pre><p>One keyword. What it actually does, concretely:</p><ul><li>Every write to a volatile field goes straight to main memory — not just the writing thread&#39;s cache.</li><li>Every read of a volatile field goes straight to main memory — not a possibly-stale cached copy.</li><li>The compiler is forbidden from hoisting, reordering across, or eliminating reads/writes of that field the way it could with a plain field.</li></ul><p>That’s the mechanical fix. But there’s a stronger, more useful guarantee hiding inside it, and it’s the one that actually matters once your code is more than a single boolean flag.</p><h3>4. happens-before — The Guarantee You&#39;re Actually Relying On</h3><p>A volatile write doesn&#39;t just make <em>that field</em> visible. It creates a <strong>happens-before</strong> relationship: everything the writing thread did <em>before</em> the volatile write becomes visible to any thread that reads that field <em>after</em> — not just the field itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eyuL_4M-c27jYfQpEB5Nrw.png" /></figure><pre>class Config {<br>    private int data;<br>    private volatile boolean ready;<br><br>    void writer() {<br>        data = 42;        // (1) plain write<br>        ready = true;     // (2) volatile write<br>    }<br><br>    void reader() {<br>        if (ready) {                  // (3) volatile read<br>            System.out.println(data); // (4) guaranteed to print 42, never 0<br>        }<br>    }<br>}</pre><p>data is a plain field. By itself, a plain field does not guarantee visibility between threads. However, ready acts as a <strong>publication flag</strong>. The writer first updates data and then performs a volatile write to ready:</p><pre>data = 42;        // happens first<br>ready = true;     // publishes the previous write</pre><p>The reader first performs a volatile read of ready and only then reads data:</p><pre>if (ready) {      // observes the volatile write<br>    System.out.println(data);<br>}</pre><p>The important rule is: <strong>a volatile write happens-before a subsequent volatile read that observes that write</strong>.</p><p>Therefore, when the reader observes ready == true, the writes performed by the writer <strong>before</strong> ready = true are guaranteed to be visible to the reader. Since data = 42 happened before the volatile write, the reader is guaranteed to see data == 42.</p><p>In other words:</p><pre>data = 42<br>    ↓<br>ready = true       ← volatile write<br>    ↓<br>    happens-before<br>    ↓<br>ready == true      ← volatile read<br>    ↓<br>read data          → guaranteed to see 42</pre><p>This is why volatile can be used as a <strong>publication mechanism</strong>: the volatile field does not just make ready visible; it also makes the writes that occurred before its volatile write visible to a thread that observes that write. If reader directly sees the data this guarantee won’t be provided.</p><p>happens-before isn&#39;t unique to volatile. The same guarantee is established by:</p><ul><li>Acquiring/releasing a synchronized block on the same monitor</li><li>A Thread.start() call (everything before start() is visible inside the new thread)</li><li>A Thread.join() returning (everything the joined thread did is visible after)</li><li>Every ExecutorService.submit() (the framework establishes happens-before between submission and task execution — this is <em>why</em> handing work to a pool is safe without you manually reasoning about visibility every time)</li></ul><p>That last point is worth sitting with: every thread pool and every CompletableFuture chain from Part 1 of this series has been relying on happens-before guarantees the entire time, even though nothing in that article mentioned it. submit() and thenApply() aren&#39;t just convenient APIs — they&#39;re also visibility boundaries.</p><h3>5. What volatile Doesn&#39;t Fix</h3><p>This is the part that trips people up in interviews specifically because it sounds like it should work:</p><pre>private volatile int counter = 0;<br><br>void increment() {<br>    counter++;   // NOT ATOMIC, even though counter is volatile<br>}</pre><p>counter++ is read-modify-write: read counter, add one, write it back. volatile guarantees each of those individual reads and writes is visible — it does <strong>nothing</strong> to stop two threads from both reading 5, both computing 6, and both writing 6, losing an increment. Ten threads calling increment() a thousand times each will not reliably produce 10,000. volatile fixed visibility; it never touched atomicity.</p><p>For that, you need either a lock (synchronized, ReentrantLock) around the whole read-modify-write sequence, or a class built for exactly this — AtomicInteger.incrementAndGet(), LongAdder, etc. — which is where Part 3 of this series picks up.</p><h3>6. When to Reach for volatile</h3><p>A quick, honest rule of thumb:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wxLcgvy7VkOO7coZbi_jMg.png" /></figure><p>That last row is a useful trick worth naming explicitly: instead of making three related fields each volatile — which gives you visibility on each one <em>individually</em>, but no guarantee about seeing them all in a consistent combination — build an immutable object holding all three, and make a single volatile reference to <em>that</em> object. One happens-before edge now covers the whole group at once.</p><h3>7. The Mental Model to Keep</h3><blockquote><em>A plain field read is not guaranteed to see another thread’s plain field write, ever — that’s not a bug, it’s the specification. </em><em>volatile doesn&#39;t just fix one field; it opens a happens-before window that drags everything written before it along, visible to whatever reads it after. Every safe concurrency primitive in Java — locks, thread pools, </em><em>CompletableFuture — is really just a different way of establishing that same happens-before edge.</em></blockquote><p>Part 1 showed you how to hand work to threads without managing them by hand. This part is what was quietly making that safe. Part 3 [<a href="https://medium.com/@rajatraghav7797/java-concurrency-async-the-complete-picture-4aeac4c6ad85?sharedUserId=rajatraghav7797"><strong><em>LINK</em></strong></a>]picks up where volatile runs out — atomicity, locks, and the classic deadlock and producer-consumer problems that come with them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b89604945e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Polling the Outbox Doesn’t Scale (And Why Your Database Already Knows Every Change)]]></title>
            <link>https://medium.com/@rajatraghav7797/why-polling-the-outbox-doesnt-scale-and-why-your-database-already-knows-every-change-b49c4b5a36b2?source=rss-d50c9c063b6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b49c4b5a36b2</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Rajat Kumar]]></dc:creator>
            <pubDate>Wed, 05 Aug 2026 05:14:58 GMT</pubDate>
            <atom:updated>2026-08-05T05:14:58.982Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous article, we solved one of the hardest problems in distributed systems.</p><p>Instead of trying to commit MySQL and Kafka together, we introduced a simple Outbox table. Every business transaction now looked like this.</p><pre>BEGIN;<br><br>INSERT INTO payments (...);<br><br>INSERT INTO outbox (...);<br><br>COMMIT;</pre><p>A separate publisher continuously read the Outbox table and published events to Kafka. No events were lost. No distributed transactions. Everything worked beautifully. Until traffic started growing.</p><h3>The Publisher Never Sleeps</h3><p>Our publisher runs in an infinite loop.</p><pre>Read 100 events<br><br>↓<br><br>Publish to Kafka<br><br>↓<br><br>Delete published events<br><br>↓<br><br>Repeat</pre><p>The SQL query is simple.</p><pre>SELECT *<br>FROM outbox<br>ORDER BY id<br>LIMIT 100;</pre><p>Whenever new events appear, they’re picked up and delivered to Kafka. Simple. Reliable. Easy to understand. So where’s the problem?</p><h3>What Happens When Nothing Happens?</h3><p>Imagine it’s 3 a.m. Almost nobody is making payments. The Outbox table is empty. Our publisher still wakes up every few milliseconds and asks:</p><pre>SELECT *<br>FROM outbox<br>ORDER BY id<br>LIMIT 100;</pre><p>The database replies:</p><blockquote><em>Nothing.</em></blockquote><p>A few milliseconds later…</p><pre>SELECT *<br>FROM outbox<br>ORDER BY id<br>LIMIT 100;</pre><p>Again…</p><blockquote><em>Nothing.</em></blockquote><p>This continues all night.</p><h3>One Publisher Isn’t A Problem</h3><p>Suppose the publisher polls every 100 milliseconds. That’s only ten queries per second. Not a big deal. But modern companies don’t run one service. They run hundreds. Imagine this.</p><ul><li>Payment Service</li><li>Order Service</li><li>Inventory Service</li><li>Notification Service</li><li>Loyalty Service</li><li>Invoice Service</li><li>Shipping Service</li></ul><p>Every service has its own Outbox. Every publisher polls its own database. Even when absolutely nothing has changed. Thousands of SQL queries every second are doing only one thing: Asking the database,</p><blockquote><em>&quot;Anything new?&quot;</em></blockquote><p>And the database keeps answering,</p><blockquote><em>&quot;No.&quot;</em></blockquote><h3>Can We Just Add An Index?</h3><p>A common suggestion is:</p><blockquote><em>&quot;Let&#39;s index the Outbox table.&quot;</em></blockquote><p>That&#39;s a good instinct. Indexes certainly help find rows faster. But they don&#39;t solve the real problem. The publisher is still asking the database the same question again and again. Whether the lookup takes one millisecond or one microsecond... it&#39;s still unnecessary work when nothing has changed. The bottleneck isn&#39;t searching. It&#39;s polling.</p><h3>A Different Question</h3><p>Instead of asking the database repeatedly,</p><blockquote><em>&quot;Did anything change?&quot;</em></blockquote><p>What if the database could simply tell us? Imagine these two conversations.</p><h3>Polling</h3><pre>Publisher → Database<br><br>Anything new?<br><br>No.<br><br>Anything new?<br><br>No.<br><br>Anything new?<br><br>No.</pre><p>Now compare that with this.</p><h3>Push</h3><pre>Database<br><br>↓<br><br>Something changed!<br><br>↓<br><br>Publisher</pre><p>Much better. The publisher does absolutely nothing until there&#39;s real work to do. But how could a database possibly know that something changed?</p><h3>Here&#39;s The Interesting Part</h3><p>Every relational database already knows. In fact, it has to. Imagine you execute this query.</p><pre>UPDATE payments<br>SET status = &#39;SUCCESS&#39;<br>WHERE id = 123;</pre><p>You might think the database immediately updates the table on disk. Surprisingly... that&#39;s not what happens.</p><h3>Inside The Database</h3><p>When the update arrives, PostgreSQL first modifies the page in memory.</p><pre>Application<br><br>↓<br><br>Memory (Shared Buffers)</pre><p>The page on disk isn&#39;t updated immediately. Writing directly to disk every time would be far too slow. Instead, PostgreSQL performs something much smarter.</p><h3>The Secret Notebook</h3><p>Before declaring the transaction successful, PostgreSQL writes a small record to a special append-only file called the <strong>Write-Ahead Log</strong>, or <strong>WAL</strong>. Conceptually, it looks something like this.</p><pre>Transaction 582<br><br>UPDATE payments<br><br>Status:<br>PENDING → SUCCESS</pre><p>Only after this log entry has been safely written to disk does PostgreSQL tell the application:</p><blockquote><strong><em>COMMIT successful.</em></strong></blockquote><p>The actual table pages can be written much later by background processes.</p><h3>Why Go Through All This Trouble?</h3><p>Imagine the server crashes immediately after the commit. The table pages may never have reached disk. Without the WAL, the database would lose committed transactions. Instead, PostgreSQL simply replays the WAL during startup.</p><pre>Crash<br><br>↓<br><br>Restart<br><br>↓<br><br>Read WAL<br><br>↓<br><br>Replay Changes<br><br>↓<br><br>Database Restored</pre><p>That&#39;s why the WAL exists. Not just for performance. But to guarantee durability.</p><h3>Wait A Second...</h3><p>If every committed transaction is already recorded in the WAL... then the database already has a perfect history of every insert, update, and delete. That raises an interesting question. Why are we repeatedly polling tables? Why not simply read the stream of committed changes?</p><h3>That&#39;s Exactly What CDC Does</h3><p>Change Data Capture, or <strong>CDC</strong>, doesn&#39;t repeatedly query your tables. Instead, it reads the database&#39;s transaction log. For PostgreSQL, that&#39;s the WAL. For MySQL, it&#39;s the Binary Log (Binlog). As soon as a transaction commits, the change appears in the log. CDC tools stream those changes almost immediately. No polling. No wasted queries. No repeatedly asking the database whether something changed.</p><h3>Meet Debezium</h3><p>One of the most popular CDC platforms is <strong>Debezium</strong>. Instead of behaving like an application issuing SQL queries, Debezium behaves much like a replication client.</p><pre>               PostgreSQL<br><br>                     │<br><br>             Write WAL Record<br><br>                     │<br><br>          ┌──────────┴──────────┐<br><br>          ▼                     ▼<br><br>   Read Replica           Debezium<br><br>                                │<br><br>                                ▼<br><br>                              Kafka</pre><p>Every committed transaction is streamed directly from the database log into Kafka. The Outbox Publisher disappears completely.</p><h3>What Changed?</h3><p>Let&#39;s compare both approaches.</p><h3>Polling</h3><pre>Application<br><br>↓<br><br>Outbox<br><br>↓<br><br>Publisher<br><br>↓<br><br>Kafka</pre><p>The publisher constantly queries the database.</p><h3>CDC</h3><pre>Application<br><br>↓<br><br>Outbox<br><br>↓<br><br>WAL<br><br>↓<br><br>Debezium<br><br>↓<br><br>Kafka</pre><p>No polling. The database simply streams committed changes. The solution scales naturally because it reuses infrastructure the database already maintains for crash recovery and replication.</p><h3>Debezium Isn&#39;t Magic</h3><p>When people first hear about Debezium, it often sounds like another complex piece of infrastructure. In reality, it&#39;s doing something remarkably simple. The database already records every committed transaction. Debezium simply reads that stream and forwards it to Kafka. It&#39;s not inventing a new mechanism. It&#39;s taking advantage of one the database already depends on.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b49c4b5a36b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>