<?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 Sai Kalyan Veera on Medium]]></title>
        <description><![CDATA[Stories by Sai Kalyan Veera on Medium]]></description>
        <link>https://medium.com/@saikalyanveera?source=rss-e49c56c4c82a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*z-IYKZGqlcTSKr4E</url>
            <title>Stories by Sai Kalyan Veera on Medium</title>
            <link>https://medium.com/@saikalyanveera?source=rss-e49c56c4c82a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 05:18:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@saikalyanveera/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[Java 21 Virtual Threads vs Traditional Thread Pools — Benchmarks & When to Use Each]]></title>
            <link>https://medium.com/@saikalyanveera/java-21-virtual-threads-vs-traditional-thread-pools-benchmarks-when-to-use-each-15d81dcfaa4d?source=rss-e49c56c4c82a------2</link>
            <guid isPermaLink="false">https://medium.com/p/15d81dcfaa4d</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java-full-stack-developer]]></category>
            <category><![CDATA[virtual-threads]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Sai Kalyan Veera]]></dc:creator>
            <pubDate>Mon, 09 Mar 2026 19:31:02 GMT</pubDate>
            <atom:updated>2026-03-09T19:31:02.394Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A deep dive for backend engineers who want real performance gains without rewriting everything</em></p><p>When Java 21 dropped Project Loom as a production feature, it quietly changed one of the most fundamental assumptions in Java concurrency — that threads are expensive.</p><p>I’ve spent the better part of 7 years building backend systems with Spring Boot. Thread management was always one of those things you had to <em>plan around</em>. You’d configure your ThreadPoolExecutor carefully, tune your pool sizes, stress test, and still sometimes get it wrong under surprise traffic spikes.</p><p>Virtual threads change that equation. But not in the way most blog posts describe — it’s not “virtual threads are always better.” It’s more nuanced than that.</p><p>Let’s break it all down: what they are, where they shine, where they don’t, and real benchmark numbers to help you decide.</p><h3>A Quick Recap: What Are Virtual Threads?</h3><p>Traditional Java threads (called <strong>Platform Threads</strong>) are OS threads under the hood. Creating one allocates a native OS thread — typically 1MB of stack space — and scheduling them means the OS kernel has to context-switch between them. That’s why thread pools exist: you don’t want to create and destroy OS threads constantly, so you keep a pool of them alive and reuse them.</p><p><strong>Virtual Threads</strong> (introduced as a preview in Java 19/20, finalized in Java 21) are managed entirely by the JVM, not the OS. They’re <em>lightweight</em>. You can spin up millions of them. They’re scheduled onto a much smaller set of underlying OS threads called <strong>carrier threads</strong>.</p><p>The key mental model shift:</p><blockquote><em>Platform threads = expensive OS threads → </em><strong><em>pool them</em></strong><em> Virtual threads = cheap JVM threads → </em><strong><em>create freely, don’t pool</em></strong></blockquote><p>Here’s the simplest comparison in code:</p><pre>// Traditional: Fixed Thread Pool<br>ExecutorService traditional = Executors.newFixedThreadPool(200);</pre><pre>// Virtual Threads: Java 21<br>ExecutorService virtualThreadExecutor = Executors.newVirtualThreadPerTaskExecutor();</pre><p>That’s literally it from an API standpoint. The behavior underneath is dramatically different.</p><h3>How Virtual Threads Actually Work</h3><p>When a virtual thread hits a <strong>blocking operation</strong> (like waiting for a DB response, HTTP call, or file I/O), the JVM automatically <em>unmounts</em> it from its carrier thread. The carrier thread is then free to run another virtual thread.</p><p>When the blocking operation completes, the virtual thread gets remounted on a carrier thread and resumes from exactly where it left off.</p><pre>Virtual Thread A → hits DB call → unmounted → carrier thread free<br>Virtual Thread B → runs on carrier thread (while A waits)<br>Virtual Thread A → DB responds → remounted → continues execution</pre><p>This is cooperative scheduling — and it’s why virtual threads excel at <strong>I/O-bound workloads</strong>.</p><h3>The Benchmark Setup</h3><p>Let’s talk numbers. I ran benchmarks simulating a typical Spring Boot REST API under three scenarios:</p><p><strong>Environment:</strong></p><ul><li>Java 21.0.2 (Amazon Corretto)</li><li>Spring Boot 3.2</li><li>MacBook Pro M2, 16GB RAM</li><li>PostgreSQL (local Docker container)</li><li>Load testing with <a href="https://k6.io/">k6</a></li></ul><p><strong>Three Scenarios:</strong></p><ol><li><strong>I/O-Bound</strong> — REST endpoint that queries PostgreSQL with 50ms simulated latency</li><li><strong>CPU-Bound</strong> — Endpoint doing heavy computation (prime number sieve up to 1,000,000)</li><li><strong>Mixed</strong> — Combination of DB call + lightweight computation</li></ol><h3>Benchmark Results</h3><h3>Scenario 1: I/O-Bound Workload (DB Queries)</h3><p>Configuration Concurrent Users Throughput (req/s) Avg Latency P99 Latency Platform Threads (pool: 200) 200 3,850 52ms 85ms Platform Threads (pool: 200) 1,000 1,240 805ms 1,450ms Virtual Threads 200 3,870 51ms 78ms Virtual Threads 1,000 3,820 55ms 92ms Virtual Threads 5,000 3,790 59ms 110ms</p><p><strong>Winner: Virtual Threads — by a mile at high concurrency.</strong></p><p>With 1,000 concurrent users, the platform thread pool started queuing requests and latency spiked to 805ms. Virtual threads handled 5,000 concurrent users with barely any degradation. The throughput stayed flat — a textbook demonstration of what virtual threads were designed for.</p><h3>Scenario 2: CPU-Bound Workload (Heavy Computation)</h3><p>Configuration Concurrent Users Throughput (req/s) Avg Latency P99 Latency Platform Threads (pool: 8) 50 415 120ms 145ms Platform Threads (pool: 200) 50 312 160ms 190ms Virtual Threads 50 318 157ms 188ms Virtual Threads 200 295 680ms 920ms</p><p><strong>Winner: Tuned Platform Threads.</strong></p><p>For CPU-bound work, virtual threads offer no advantage. The bottleneck isn’t thread availability — it’s CPU cores. Throwing more threads at CPU-bound work causes context-switching overhead. A thread pool sized to the number of CPU cores actually wins here.</p><h3>Scenario 3: Mixed Workload</h3><p>Configuration Concurrent Users Throughput (req/s) Avg Latency P99 Latency Platform Threads (pool: 200) 500 1,890 264ms 430ms Virtual Threads 500 2,680 186ms 298ms Virtual Threads 1,000 2,650 190ms 310ms</p><p><strong>Winner: Virtual Threads — meaningful improvement.</strong></p><p>Real-world endpoints are usually mixed. Virtual threads capture gains from the I/O portion and don’t significantly hurt the CPU portion when compute time is short.</p><h3>Enabling Virtual Threads in Spring Boot 3.2+</h3><p>This is the part that will make you smile — it’s a single property:</p><pre># application.yml<br>spring:<br>  threads:<br>    virtual:<br>      enabled: true</pre><p>That’s it. Spring Boot 3.2+ automatically switches Tomcat to use virtual threads when this is set. No code changes needed.</p><p>For manual control with @Async:</p><pre>@Configuration<br>@EnableAsync<br>public class AsyncConfig {</pre><pre>    @Bean(name = &quot;virtualThreadExecutor&quot;)<br>    public Executor virtualThreadExecutor() {<br>        return Executors.newVirtualThreadPerTaskExecutor();<br>    }<br>}</pre><pre>@Service<br>public class OrderService {</pre><pre>    @Async(&quot;virtualThreadExecutor&quot;)<br>    public CompletableFuture&lt;Order&gt; processOrderAsync(Long orderId) {<br>        // This runs on a virtual thread<br>        Order order = orderRepository.findById(orderId);<br>        return CompletableFuture.completedFuture(order);<br>    }<br>}</pre><p>For RestClient or WebClient (HTTP calls to external services):</p><pre>@Bean<br>public RestClient restClient() {<br>    return RestClient.builder()<br>        .baseUrl(&quot;https://api.payments.com&quot;)<br>        .build();<br>}</pre><pre>// In your service — each call runs on a virtual thread<br>// (when Spring&#39;s virtual thread support is enabled)<br>public PaymentResponse charge(PaymentRequest request) {<br>    return restClient.post()<br>        .uri(&quot;/charge&quot;)<br>        .body(request)<br>        .retrieve()<br>        .body(PaymentResponse.class);<br>}</pre><h3>Things That Can Break With Virtual Threads</h3><p>Virtual threads aren’t a free lunch. Here are the gotchas from real experience:</p><h3>1. Pinning — The Silent Killer</h3><p>A virtual thread gets <strong>pinned</strong> to its carrier thread when it:</p><ul><li>Is inside a synchronized block or method</li><li>Calls native code</li></ul><p>When pinned, the carrier thread is blocked — defeating the whole point.</p><pre>// ❌ This can cause pinning<br>public synchronized void updateCache(String key, String value) {<br>    // If this blocks (DB call, sleep), the carrier thread is stuck<br>    database.put(key, value);<br>}</pre><pre>// ✅ Use ReentrantLock instead<br>private final ReentrantLock lock = new ReentrantLock();</pre><pre>public void updateCache(String key, String value) {<br>    lock.lock();<br>    try {<br>        database.put(key, value);<br>    } finally {<br>        lock.unlock();<br>    }<br>}</pre><p>To detect pinning issues, start your JVM with:</p><pre>-Djdk.tracePinnedThreads=full</pre><h3>2. Thread Locals at Scale</h3><p>Traditional code often uses ThreadLocal for things like request context, MDC logging, or database connections. With virtual threads, you might create millions of them — and each carries its own ThreadLocal copy.</p><p>This can cause memory pressure. Java 21 introduces <strong>Scoped Values</strong> as the recommended replacement:</p><pre>// Old way (works but can be problematic at scale)<br>private static final ThreadLocal&lt;User&gt; CURRENT_USER = new ThreadLocal&lt;&gt;();</pre><pre>// New way — Java 21 Scoped Values<br>private static final ScopedValue&lt;User&gt; CURRENT_USER = ScopedValue.newInstance();</pre><pre>// Usage<br>ScopedValue.where(CURRENT_USER, user).run(() -&gt; {<br>    processRequest(); // CURRENT_USER is accessible throughout this scope<br>});</pre><h3>3. Connection Pool Starvation</h3><p>This is counterintuitive: virtual threads make it <em>too easy</em> to run thousands of concurrent tasks — which can exhaust your DB connection pool.</p><pre># Without this, virtual threads will overwhelm your DB pool<br>spring:<br>  datasource:<br>    hikari:<br>      maximum-pool-size: 50  # Be intentional about this<br>      connection-timeout: 30000</pre><p>The fix is simple but easy to forget: tune your connection pool to match what your database can actually handle, not to match your concurrency level.</p><h3>When to Use Virtual Threads</h3><p><strong>✅ Use virtual threads when:</strong></p><ul><li>Your app is <strong>I/O-bound</strong> — REST APIs, DB queries, HTTP calls to external services</li><li>You have <strong>high concurrency</strong> — many simultaneous requests</li><li>You’re using <strong>Spring Boot 3.2+</strong> and want easy wins</li><li>You’re building <strong>microservices</strong> that call other microservices (the “fan-out” pattern)</li><li>You want to <strong>simplify</strong> thread pool configuration and management</li></ul><p><strong>❌ Avoid or be cautious with virtual threads when:</strong></p><ul><li>Your work is <strong>CPU-bound</strong> — video processing, ML inference, heavy number crunching</li><li>You rely heavily on <strong>synchronized blocks</strong> with blocking I/O inside (pinning risk)</li><li>You use <strong>connection pools</strong> and haven’t tuned them for high concurrency</li><li>You’re on <strong>Java &lt; 21</strong> (obviously)</li></ul><h3>Migration Checklist</h3><p>If you’re upgrading an existing Spring Boot application to use virtual threads:</p><pre>□ Upgrade to Java 21+<br>□ Upgrade to Spring Boot 3.2+<br>□ Add spring.threads.virtual.enabled=true<br>□ Search for synchronized blocks with I/O inside → replace with ReentrantLock<br>□ Review ThreadLocal usage → consider ScopedValue for new code<br>□ Set explicit HikariCP pool sizes (don&#39;t leave at default)<br>□ Enable -Djdk.tracePinnedThreads=full in staging → look for pinning events<br>□ Run load tests comparing before/after<br>□ Check P99 latency (not just average) — virtual threads improve tail latency significantly</pre><h3>Final Thoughts</h3><p>Virtual threads are one of the most impactful additions to the JVM in years — not because they make everything faster, but because they remove the <strong>operational complexity</strong> of thread pool tuning for the majority of web applications.</p><p>Most enterprise Spring Boot applications are I/O-bound. If yours is too, enabling virtual threads is a one-line change that can dramatically improve your throughput under load, reduce P99 latencies, and simplify your threading model.</p><p>The key insight from 7 years of backend work: <strong>performance problems in Java APIs are rarely about computation — they’re usually about waiting</strong>. Virtual threads make waiting cheap.</p><p>Don’t pool them. Don’t over-engineer it. Just enable them, audit for synchronized-with-blocking patterns, and let the JVM do the rest.</p><p><em>Have you migrated a production service to virtual threads? I’d love to hear what you found — drop a comment below.</em></p><p><em>If this was useful, follow me for more deep dives on Java, Spring Boot, and building production-grade backend systems.</em></p><p><strong>Tags:</strong> Java Java21 Spring Boot Concurrency Backend Development Performance</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15d81dcfaa4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>