<?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 Deepankar Gusain on Medium]]></title>
        <description><![CDATA[Stories by Deepankar Gusain on Medium]]></description>
        <link>https://medium.com/@iamdeepankargusain?source=rss-8a2463cc3f5f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*JYwa5nz0SJNFoTZO</url>
            <title>Stories by Deepankar Gusain on Medium</title>
            <link>https://medium.com/@iamdeepankargusain?source=rss-8a2463cc3f5f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 05:53:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@iamdeepankargusain/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 End of Reactive Java? Surviving the Virtual Thread Revolution in Spring Boot]]></title>
            <link>https://medium.com/@iamdeepankargusain/the-end-of-reactive-java-surviving-the-virtual-thread-revolution-in-spring-boot-a43cb21f5a9e?source=rss-8a2463cc3f5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a43cb21f5a9e</guid>
            <category><![CDATA[reactive-java]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java-multithreading]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[virtual-threads]]></category>
            <dc:creator><![CDATA[Deepankar Gusain]]></dc:creator>
            <pubDate>Wed, 30 Sep 2026 00:14:11 GMT</pubDate>
            <atom:updated>2026-09-30T00:14:11.671Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve built highly concurrent Java applications over the last five years, you’re intimately familiar with the “Reactive Tax.”</p><p>You wanted to handle tens of thousands of concurrent requests without exhausting your Tomcat thread pool. So, you ripped out your standard Spring MVC controllers and rewrote them in Spring WebFlux. You traded standard imperative code for a maze of Mono, Flux, and chained operators. You lost the ability to read a simple stack trace, and debugging became a nightmare—all in the name of non-blocking I/O.</p><p>But with Java 21 LTS and Spring Boot 3.2+ (now deeply integrated into Spring Boot 4), the rules of the game have fundamentally changed. Project Loom’s <strong>Virtual Threads</strong> allow us to write simple, sequential, blocking code that scales exactly like a reactive application.</p><p>Does this mean reactive programming is dead? And more importantly, is flipping spring.threads.virtual.enabled=true a magic bullet, or a trap?</p><p>Let’s break down the paradigm shift, the architectural mechanics, and the hidden pitfalls of deploying Virtual Threads in production.</p><h3>Why Platform Threads Failed Us</h3><p>In traditional Java, every java.lang.Thread is a &quot;Platform Thread,&quot; directly wrapping a 1:1 Operating System thread.</p><p>OS threads are heavy. Creating one consumes roughly 1MB of memory for the thread stack. If your server handles 5,000 concurrent requests blocking on a slow database query, you need 5,000 threads. That’s 5GB of RAM <em>just</em> for the threads, plus the massive CPU overhead of the OS scheduler context-switching between them.</p><p>When your thread pool runs out, requests queue up. When the queue fills, your API drops requests.</p><h3>The Magic of the “Unmount”</h3><p>Virtual Threads flip the script. They are lightweight, JVM-managed entities. You can create millions of them on a standard laptop because they consume just kilobytes of memory.</p><p>Instead of a 1:1 mapping, millions of Virtual Threads are mapped to a small pool of OS “Carrier Threads” (typically equal to your CPU core count).</p><p>Here is the magic: When a Virtual Thread hits a blocking operation — like calling restTemplate.getForObject() or executing a JDBC query—it doesn&#39;t block the underlying OS thread. Instead, the JVM <strong>unmounts</strong> the Virtual Thread from the Carrier Thread and stores its state on the heap. The Carrier Thread is immediately free to mount and execute <em>another</em> Virtual Thread. Once the database responds, the original Virtual Thread is re-queued and resumes exactly where it left off.</p><p>You get the performance of WebFlux with the readability of standard Java.</p><h3>The 3 Hidden Pitfalls of Production</h3><p>It sounds too good to be true, and without the right guardrails, it is. If you enable Virtual Threads today, you must watch out for three critical traps.</p><h3>1. The Silent Killer: Thread Pinning</h3><p>When a Virtual Thread unmounts, it frees the Carrier Thread. However, if a Virtual Thread executes a synchronized block or a native method, the JVM cannot unmount it. It becomes <strong>pinned</strong> to the OS thread.</p><p>If your code executes a slow I/O operation inside a synchronized block, the underlying OS thread is completely blocked. If you pin all your Carrier Threads, your application grinds to a halt—often worse than it would have with traditional threads.</p><p><strong>The Fix:</strong> Modernize your concurrency. Replace all synchronized blocks with ReentrantLock from java.util.concurrent.locks. ReentrantLock is fully Loom-aware and will not pin the Virtual Thread. <em>(Note: The JVM team is actively working to eliminate this limitation in future Java releases, but for now, it remains a severe bottleneck).</em></p><h3>2. Overwhelming the Downstream (The Missing Throttle)</h3><p>In the old days, your HikariCP database connection pool had 50 connections, and your Tomcat thread pool had 200 threads. The thread pool acted as a natural throttle. If traffic spiked, requests queued up at the Tomcat level, protecting your database from a stampede.</p><p>With Virtual Threads, that throttle is gone. You can easily accept 10,000 concurrent requests instantly. If all 10,000 virtual threads immediately ask for a database connection, your Hikari pool will block 9,950 of them. Worse, if they make concurrent HTTP calls to a downstream microservice, you essentially launch a self-inflicted DDoS attack against your own architecture.</p><p><strong>The Fix:</strong> You must implement explicit backpressure. Use Semaphore permits or resilience libraries like Resilience4j (Bulkheads) to artificially limit concurrent access to expensive external resources.</p><h3>3. Do Not Pool Virtual Threads</h3><p>Old habits die hard. For decades, we pooled threads because they were expensive to create.</p><p>Virtual Threads are ephemeral. Creating them takes microseconds. If you submit a Virtual Thread to a traditional ThreadPoolExecutor, you are adding unnecessary management overhead and completely missing the point of Project Loom.</p><p><strong>The Fix:</strong> Never pool Virtual Threads. Use the “Thread-Per-Task” model. When you need to execute parallel work, spin up a new Virtual Thread using Executors.newVirtualThreadPerTaskExecutor() or Java 21&#39;s StructuredTaskScope, let it do its job, and let the Garbage Collector destroy it.</p><h3>Is Reactive Dead?</h3><p>If your application is CPU-bound (e.g., video encoding, heavy cryptographic hashing), Virtual Threads will not help you. But for the 95% of enterprise Java apps that are I/O bound — spending their lives waiting on databases, caches, and external APIs — Virtual Threads are the most significant upgrade since Lambdas in Java 8.</p><p>Reactive programming still has a home in highly specialized, pure streaming use cases (like WebSockets or SSE data feeds). But for standard REST APIs and microservices, the era of writing Mono.zip() is drawing to a close.</p><p>Flip the switch. Update your locks. Protect your downstream resources. Welcome to the new era of Java.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a43cb21f5a9e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Taming the JVM: A Developer’s Guide to Java Heap Memory, Containers, and Defeating OutOfMemoryError]]></title>
            <link>https://medium.com/@iamdeepankargusain/taming-the-jvm-a-developers-guide-to-java-heap-memory-containers-and-defeating-outofmemoryerror-68eaecf4563c?source=rss-8a2463cc3f5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/68eaecf4563c</guid>
            <category><![CDATA[heap-memory]]></category>
            <category><![CDATA[heapdump]]></category>
            <category><![CDATA[outofmemoryerror]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Deepankar Gusain]]></dc:creator>
            <pubDate>Wed, 30 Sep 2026 00:01:32 GMT</pubDate>
            <atom:updated>2026-09-30T00:01:32.332Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve been writing Java for any meaningful amount of time, you’ve likely seen it in your logs: java.lang.OutOfMemoryError: Java Heap Space. It’s the stack trace that ruins weekends and triggers late-night pager alerts.</p><p>When the JVM gets angry — when rogue threads spawn endless objects or an unbounded HashMap swallows your heap—your application grinds to a halt. The CPU spikes to 100% as the Garbage Collector (GC) runs frantically, desperately trying to reclaim memory that simply isn’t there.</p><p>But memory management in modern Java (especially in containerized environments like Docker and Kubernetes) isn’t black magic. By understanding how to properly size your heap, allocate memory in containers, and capture the right diagnostics, you can prevent OOMs before they crash your production environment.</p><p>Let’s dive into the mechanics of Java heap memory, the “Goldilocks dilemma” of sizing, and how to troubleshoot leaks like a pro.</p><h3>1. The Goldilocks Dilemma: Large vs. Small Heap Size</h3><p>When sizing your JVM, the first question is usually: <em>Should I just give it a massive heap?</em></p><p>Memory is divided primarily between the <strong>Young Generation</strong> (where new objects are born) and the <strong>Old Generation</strong> (where long-living objects are tenured). Not everything lives in the heap, however. Things like class definitions, static variables, and thread stacks live in native memory regions like <strong>Metaspace</strong>.</p><p>Choosing the right heap size is a balancing act:</p><ul><li><strong>The Small Heap:</strong> A small heap means your GC runs frequently. The benefit? The GC pause times (Stop-The-World events) are very short. The downside? The CPU overhead of constant garbage collection is high, and unexpected traffic spikes can easily trigger an OutOfMemoryError.</li><li><strong>The Large Heap:</strong> A large heap gives your application plenty of breathing room, which is great for high-throughput applications or large datasets. The GC runs less frequently. However, when a Full GC finally <em>does</em> run, sweeping a massive, fragmented heap can cause noticeably long pause times (though modern collectors like G1GC and ZGC have drastically reduced this penalty).</li></ul><p><strong>The Verdict:</strong> Start with the minimum heap size your application genuinely requires under normal load, plus a buffer for traffic spikes. Over-provisioning memory wastes resources, while under-provisioning kills reliability.</p><h3>2. Setting the Limits: Best Practices for Containers</h3><p>In the old days of physical servers, setting -Xms (initial heap) and -Xmx (maximum heap) was straightforward. But in the era of Docker and Kubernetes, the JVM used to blindly look at the underlying <em>host</em> machine&#39;s memory, ignoring container limits. This led to the dreaded <strong>OOM-Killer (Exit Code 137)</strong>, where the Linux kernel abruptly terminates your container for exceeding its limits.</p><p>To fix this, we have a few modern strategies:</p><h3>Option A: Percentage-Based Allocation (Java 8u191+)</h3><p>If you are running modern Java versions (Java 11, 17, or 21), the best practice is to let the JVM dynamically calculate its heap based on the container’s limit using percentages.</p><p>Bash</p><pre>-XX:InitialRAMPercentage=50.0 -XX:MaxRAMPercentage=75.0</pre><p>If you deploy this in a Kubernetes pod with a 2GB memory limit, the JVM will elegantly set its max heap to 1.5GB (75%).</p><h3>Option B: The Classic -Xmx in Containers</h3><p>You can still use -Xmx, but there is a golden rule you must follow: <strong>Never set your </strong><strong>-Xmx equal to your container memory limit.</strong></p><p>If you set -Xmx2G, your container memory limit must be at least <strong>2.5GB (25% larger)</strong>. Why? Because the JVM needs memory outside of the heap:</p><ul><li><strong>Metaspace:</strong> Stores class metadata.</li><li><strong>Thread Stacks:</strong> Every thread consumes native memory (usually ~1MB per thread).</li><li><strong>Code Cache &amp; GC overhead:</strong> The JIT compiler and the Garbage Collector itself need memory to do their jobs.</li><li><strong>Off-Heap Memory:</strong> Libraries using Direct Byte Buffers bypass the heap entirely.</li></ul><p>If your heap takes 100% of the container’s allowance, native memory allocations will push the container over the edge, and Kubernetes will kill it.</p><h3>3. Diagnosing the Dreaded Memory Leak</h3><p>When an OutOfMemoryError strikes, it generally boils down to two causes:</p><ul><li><strong>Traffic Spikes:</strong> You suddenly received 3x the normal traffic, and the application legitimately needed more memory to process concurrent requests.</li><li><strong>A Memory Leak:</strong> A bug in your code is holding onto object references (like caching data in an unbounded Map), preventing the GC from cleaning them up.</li></ul><h3>The “Slope” Test via GC Logs</h3><p>You can often identify a leak before an OOM occurs just by enabling GC logging (-Xlog:gc* in Java 11+).</p><p>If you map out your memory usage after every Full GC event, a healthy application will drop back down to its baseline (a 0-degree slope). An application with a memory leak will exhibit a rising baseline after each Full GC. The memory creeps up at a 15-degree angle until the heap is entirely saturated. At that point, the JVM spends 99% of its CPU time running GC and 1% executing your code.</p><h3>4. The Developer’s Toolkit: Capturing Heap Dumps</h3><p>You can’t fix what you can’t see. To identify the exact class or data structure causing the leak, you need a Heap Dump — a binary snapshot of your JVM’s memory.</p><p>Here are the three best ways to capture one:</p><p><strong>1. The Automated Lifesaver (Best Practice)</strong> Humans forget to capture heap dumps during the heat of an ongoing production outage. Let the JVM do it for you automatically right before it crashes:</p><p>Bash</p><pre>-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/var/log/heapdump.hprof</pre><p><em>Note: Make sure your container volume is persistent, or the heap dump will disappear when the pod restarts!</em></p><p><strong>2. The On-Demand approach with </strong><strong>jcmd</strong> If you notice memory creeping up and want a snapshot of a running application:</p><p>Bash</p><pre>jcmd &lt;PID&gt; GC.heap_dump /tmp/heapdump.hprof</pre><p><strong>3. The Traditional </strong><strong>jmap</strong> If jcmd isn&#39;t available, the classic jmap utility (packaged in the JDK bin folder) does the trick. Passing the live flag ensures you only dump objects actively holding references:</p><p>Bash</p><pre>jmap -dump:live,format=b,file=heapdump.hprof &lt;PID&gt;</pre><h3>Analyzing the Dump</h3><p>Once you have the .hprof file, do not try to open it in a text editor. Use tools like <strong>Eclipse MAT (Memory Analyzer Tool)</strong>, <strong>GCeasy</strong>, or <strong>yCrash</strong>.</p><p>Navigate straight to the <strong>Largest Objects</strong> view. In 95% of memory leak cases, the culprit will be sitting right at the top — perhaps a MapManager taking up 99% of the heap. From there, trace the <strong>Incoming References</strong> to find out exactly which class in your codebase is keeping that object alive.</p><h3>Conclusion</h3><p>Mastering Java heap memory is a rite of passage for backend developers. By correctly mapping your -Xmx limits to your container sizes, monitoring your GC logs for rising baselines, and configuring automatic heap dumps on failure, you transform memory management from guesswork into an exact science.</p><p>The next time java.lang.OutOfMemoryError shows up in your logs, you won&#39;t panic. You&#39;ll just grab the heap dump, find the unbounded collection, and ship a fix.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68eaecf4563c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>