<?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 Panna on Medium]]></title>
        <description><![CDATA[Stories by Panna on Medium]]></description>
        <link>https://medium.com/@pannavr?source=rss-439eb3ac9227------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EsGXNxm7j3IZiqWqronUHg.png</url>
            <title>Stories by Panna on Medium</title>
            <link>https://medium.com/@pannavr?source=rss-439eb3ac9227------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 11:14:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pannavr/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 Virtual Threads: A New Era of Concurrency]]></title>
            <link>https://medium.com/@pannavr/java-virtual-threads-a-new-era-of-concurrency-1493fdb7c97a?source=rss-439eb3ac9227------2</link>
            <guid isPermaLink="false">https://medium.com/p/1493fdb7c97a</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-engineer]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[virtual-threads]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <dc:creator><![CDATA[Panna]]></dc:creator>
            <pubDate>Sat, 17 May 2025 09:28:36 GMT</pubDate>
            <atom:updated>2025-05-19T04:05:43.000Z</atom:updated>
            <content:encoded><![CDATA[<p>Java Virtual Threads: A New Era of Concurrency</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1_gUwCB2NHvOg5De0KN21A.png" /><figcaption>Image generated by Gemini</figcaption></figure><p>When discussing threads in Java, we inevitably talk about concurrency. For those unfamiliar, concurrency simply means a system’s ability to handle multiple tasks by switching between them quickly, making it seem like everything is happening simultaneously.</p><p>In Java, concurrency is typically implemented using <strong>Threads </strong>or the <strong>ExecutorService</strong>. However, this traditional approach comes with some well-known challenges:</p><blockquote>Creating and running threads in Java is relatively heavy, as each thread maps directly to an underlying OS thread.</blockquote><blockquote>Each conventional thread requires a large stack memory (around 1MB).</blockquote><blockquote>For large-scale applications like HTTP servers or microservices, this can become a scalability bottleneck, as the system struggles to manage thousands or even millions of threads concurrently.</blockquote><p>This is where <a href="https://cr.openjdk.org/~rpressler/loom/Loom-Proposal.html"><strong>Project Loom</strong></a><strong> </strong>comes in, aiming to simplify Java’s concurrency model. By introducing the concept of Virtual Threads, Java offers a new way to create thousands of lightweight threads that are far more efficient, ideal for I/O-bound applications like web servers, database handlers, or microservices that require many parallel connections.</p><p>With virtual threads, we can write code in an imperative (sequential and readable) style while still achieving high scalability and performance, without the added complexity of reactive programming or callback hell.</p><p>🧠 <strong>What is a Virtual Thread?</strong></p><p><strong>Virtual Threads </strong>are a new type of thread introduced as part of <a href="https://cr.openjdk.org/~rpressler/loom/Loom-Proposal.html">Project Loom</a> in Java 19, and officially became a stable feature starting with Java JDK 21.</p><p>Unlike traditional threads (commonly referred to as <em>platform threads</em>), virtual threads are not directly tied to operating system (OS) threads. Instead, they are managed by the <strong>Java Virtual Machine (JVM)</strong>, similar to <em>green threads</em> in other languages (such as <em>goroutines</em> in Go or <em>lightweight processes</em> in Erlang).</p><p><strong>⚙️ Quick Comparison:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*jhspxah1SqHYvMtTmucUHA.png" /></figure><p>🚀 <strong>How to Run Virtual Threads in Java 21+</strong><br> To start using virtual threads, make sure you’re running <strong>Java 21</strong> or a later version.</p><p>🧪 <strong>Basic Example:</strong></p><pre>public class Main {<br>    public static void main(String[] args) {<br>        Runnable task = () -&gt; System.out.println(&quot;Hello from Virtual Thread: &quot; + Thread.currentThread());<br>        Thread.startVirtualThread(task);<br><br>        try {<br>            Thread.sleep(100); // Add a small delay to allow the output to appear<br>        } catch (InterruptedException e) {<br>            e.printStackTrace();<br>        }<br>    }<br>}</pre><p>Without using an ExecutorService, we can directly create and run a virtual thread using just Thread.startVirtualThread(...).</p><p>🛠️ <strong>Using ExecutorService:</strong></p><pre>try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {<br>    for (int i = 0; i &lt; 1000; i++) {<br>        int taskId = i;<br>        executor.submit(() -&gt; {<br>            Thread.sleep(1000);<br>            System.out.println(&quot;Task &quot; + taskId + &quot; done in &quot; + Thread.currentThread());<br>            return null;<br>        });<br>    }<br>}</pre><p>This executor creates a new virtual thread for each task, ideal for handling many fast, parallel tasks in applications like REST servers.</p><p>📌 <strong>Lightweight Case Study: Simulating 100,000 Tasks</strong><br> Curious about the power of virtual threads? Try comparing the following code:</p><pre>  public static void main(String[] args) throws InterruptedException {<br>        int taskCount = 100_000;<br>        CountDownLatch latch = new CountDownLatch(taskCount);<br>        Instant start = Instant.now();<br>        try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {<br>            IntStream.range(0, taskCount).forEach(i -&gt;<br>                    executor.submit(() -&gt; {<br>                        try {<br>                            Thread.sleep(1000);<br>                            System.out.println(&quot;Task &quot; + i + &quot; done in &quot; + Thread.currentThread());<br>                        } catch (InterruptedException e) {<br>                            Thread.currentThread().interrupt();<br>                        } finally {<br>                            latch.countDown();<br>                        }<br>                        return null;<br>                    })<br>            );<br>            latch.await(); // Wait for all tasks to finish<br>        }<br>        Instant end = Instant.now();<br>        System.out.println(&quot;Execution Time: &quot; + Duration.between(start, end).toMillis() + &quot; ms&quot;);<br>    }</pre><p>Try running the code above while monitoring CPU and memory usage through Task Manager (Windows) or System Monitor (Linux/macOS). Even though the program executes 100,000 tasks in parallel, you will notice relatively low resource consumption. This efficiency is due to virtual threads not being directly tied to OS threads and requiring minimal memory and CPU per thread.</p><p>To compare performance with platform threads, modify the following section:</p><pre>ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();</pre><p>Change it to:</p><pre>ExecutorService executor = Executors.newFixedThreadPool(100);</pre><p>You can adjust the value of 100 according to your system’s capabilities. Run the program again and observe the differences in CPU and memory usage in Task Manager or System Monitor.</p><p>With platform threads, CPU and memory consumption are usually much higher because the number of simultaneously running threads is limited, resulting in slower processing and quicker resource exhaustion. When the task load is very large, this can lead to performance degradation or even system failure (OutOfMemoryError).</p><p>This comparison highlights the advantage of virtual threads in efficiently running thousands of concurrent tasks with significantly lower CPU and memory overhead, making them ideal for large-scale I/O-bound applications.</p><p>🤔<strong>With all the advantages virtual threads offer, when should we use virtual threads and avoid them?</strong></p><p>🔥 <strong>When Should Virtual Threads Be Used?</strong><br> Virtual threads are well-suited for I/O-bound or blocking tasks, such as:</p><ul><li>Calling external APIs</li><li>Blocking database queries</li><li>Reading/writing files</li><li>Network operations (sockets, FTP, etc.)</li></ul><p>Because they are lightweight, you can run thousands of virtual threads concurrently without wasting resources. This makes them ideal for high-traffic web servers, microservices, and batch processing workloads involving extensive blocking I/O. The code remains easy to read thanks to the familiar blocking style, while achieving scalability comparable to reactive programming.</p><p>⚠️ <strong>When Should Virtual Threads Not Be Used?</strong><br> Although powerful, virtual threads are not suitable for:</p><ul><li><strong>Heavy CPU-bound operations</strong><br> Examples include intensive mathematical computations, rendering, or machine learning inference. Since virtual threads still consume CPU and rely on JVM scheduling, traditional OS threads managed by the operating system are better suited for such heavy tasks.</li><li><strong>Code that depends on native threads or thread pinning</strong><br> Native libraries that perform blocking native calls or require threads to stay pinned (not migrate between carrier OS threads) may encounter issues, as virtual threads can switch between underlying carrier threads.</li><li><strong>Code that is not thread-safe</strong><br> Virtual threads do not automatically solve concurrency problems. Code with race conditions or data races still requires proper synchronization to avoid bugs.</li></ul><p>🎯 <strong>Conclusion</strong></p><p>Virtual threads, introduced by <a href="https://cr.openjdk.org/~rpressler/loom/Loom-Proposal.html">Project Loom</a>, represent a revolution in Java concurrency programming. They enable running thousands of lightweight threads efficiently without the heavy overhead typically associated with traditional threads that are directly tied to the operating system. Virtual threads are particularly well-suited for I/O-bound applications such as web servers, microservices, and other blocking operations. This allows developers to write simpler, more scalable code without resorting to the often complex reactive programming paradigm.</p><p>However, virtual threads are not suitable for all types of tasks. For highly CPU-intensive workloads, native libraries that require thread affinity (thread pinning), and code that is not concurrency-safe, traditional threads remain the more appropriate choice.</p><p>With a proper understanding of when and how to use virtual threads, Java developers can significantly enhance the performance and scalability of their applications in today’s modern computing environment.</p><p>📎 <strong>References &amp; Further Reading:</strong></p><blockquote><a href="https://openjdk.org/jeps/444">Java Virtual Threads Documentation (OpenJDK) </a><br> <a href="https://cr.openjdk.org/~rpressler/loom/Loom-Proposal.html">Project Loom Overview</a></blockquote><p>Thanks for reading! If you’d like to discuss or have any questions, feel free to connect with me on<a href="https://www.linkedin.com/in/pannavr/"> LinkedIn</a> or leave a comment below. Looking forward to connecting and sharing ideas!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1493fdb7c97a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>