<?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 Bhavesh Suvalaka on Medium]]></title>
        <description><![CDATA[Stories by Bhavesh Suvalaka on Medium]]></description>
        <link>https://medium.com/@bhavesh-suvalaka?source=rss-557e5a5047bd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*R57XOHXu-KM7T9nosUdy0A.png</url>
            <title>Stories by Bhavesh Suvalaka on Medium</title>
            <link>https://medium.com/@bhavesh-suvalaka?source=rss-557e5a5047bd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 06:02:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bhavesh-suvalaka/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 Deep Dive into Lightweight Concurrency]]></title>
            <link>https://medium.com/javarevisited/java-virtual-threads-a-deep-dive-into-lightweight-concurrency-4c99b29add25?source=rss-557e5a5047bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c99b29add25</guid>
            <category><![CDATA[java-virtual-threads]]></category>
            <category><![CDATA[virtual-threads]]></category>
            <category><![CDATA[concurrency-in-java]]></category>
            <dc:creator><![CDATA[Bhavesh Suvalaka]]></dc:creator>
            <pubDate>Sun, 20 Sep 2026 09:58:07 GMT</pubDate>
            <atom:updated>2026-11-01T06:17:05.931Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kQNNgD5d7J0NiNQscj1BOQ.png" /><figcaption>More concurrency, less overhead.</figcaption></figure><p><em>This article is part of a series where we explore how CPUs, operating systems, threads, and concurrency work together. If you’re new to these concepts, you can start with </em><a href="https://medium.com/@bhavesh-suvalaka/the-heart-of-computing-understanding-cpu-and-os-collaboration-8778b66fff26"><em>CPU and OS Collaboration</em></a><em> and </em><a href="https://medium.com/@bhavesh-suvalaka/breaking-through-bottlenecks-enhancing-throughput-with-threads-async-and-routines-711241b732b2"><em>Threads, Async, and Routines</em></a><em>.</em></p><h3>Virtual Threads</h3><p>In the last <a href="https://medium.com/@bhavesh-suvalaka/breaking-through-bottlenecks-enhancing-throughput-with-threads-async-and-routines-711241b732b2">blog</a>, we saw how routines/fiber came to be, java had also introduced lightweight threads called virtual threads as part of Java19 and had been released as part of Java 21 .</p><p>But how can Java create millions of virtual threads when the CPU can execute only a limited number of threads at a time? And what actually happens when a virtual thread makes a blocking call?</p><p>Let’s understand how it works internally.</p><p>As per JEP444 <a href="https://openjdk.org/jeps/444">https://openjdk.org/jeps/444 </a>, below are three major goals of virtual threads:</p><ol><li>Enable server applications written in the simple thread-per-request style to scale with near-optimal hardware utilization.</li><li>Enable existing code that uses the java.lang. Thread API to adopt virtual threads with minimal change.</li><li>Enable easy troubleshooting, debugging, and profiling of virtual threads with existing JDK tools.</li></ol><p>The benefits of virtual threads are:</p><ol><li>Uses thread-per-request style more efficiently</li><li>JVM handles the lifecycle and scheduling</li><li>It can achieve scalability similar to asynchronous programming for I/O-intensive applications.</li><li>Virtual threads are cheap to create and can be created in very large numbers.</li><li>Applications’ unit of concurrency is now the platform’s unit of concurrency</li></ol><p>If you have read this blog, you might have got the idea of why Virtual threads! Let’s understand how it works internally.</p><h3>Internals of virtual threads</h3><p>There are two main constructs which make virtual threads to run efficiently:</p><ol><li>Continuation,</li><li>Scheduling.</li></ol><h3>Continuations</h3><p>Virtual threads use continuation to carry out the assigned tasks. Continuation is a low-level internal JDK API, which has been developed primarily to enable virtual threads in Java, this might be made public as well in the future.</p><p>Continuation is an object that accepts a runnable and scope. It is cheaper than a platform thread as it doesn’t require a dedicated OS thread. You can put multiple stops in the task you want to perform and then resume when the task can be resumed. Continuation allows a task to pause and resume from where it left off.</p><p>When the task is parked, its execution state is preserved so it can resume from where it left off.</p><p>Let’s take a simplified example to understand how continuations work. This is just for reference, not actual executable Java code.</p><pre> public static void count() {<br>    var continuation = new Continuation(&quot;counter&quot;, Example::increase);<br>    try (Scanner sc = new Scanner(System.in)) {<br>      while (!continuation.isDone()) {<br>        System.out.println(&quot;Press enter to print next count&quot;);<br>        sc.nextLine();<br>        continuation.run();<br>      }<br>    }<br>  }<br><br>  public static void increase(Continuation.Scope&lt;Integer&gt; scope) {<br>    IntStream.of(10).forEach(it -&gt; Continuation.yield(scope, it));<br>  }</pre><p>In the above example, we are creating a continuation with a scope, and until continuation is done, it will increment whenever the user presses enter. Continuation.yield will yield the integer value, continuation.run will resume the process where it would have left off, and the context will be saved with the continuation scope, so when it resumes, it knows where to continue.</p><p>The Oracle folks have done a wonderful job hiding all the complexity internally, you don’t need to add the stops to park specifically, and the JVM is smart enough to park a virtual thread when it identifies an i/o call. Essentially, most of the blocking call is turned into non-blocking when it’s made from virtual threads. Simple but mind-blowing, isn’t it?</p><h3>Scheduling</h3><p>JVM uses a dedicated ForkJoinPool in FIFO mode to schedule virtual threads, with work-stealing to distribute tasks among carrier threads, also you should note this ForkJoinPool implementation is different than the common pool used for other purposes, e.g., parallel streams which operate in LIFO (Last In First Out) mode.</p><p>Virtual threads do not have the power to execute any task they need to be mounted on the platform threads to carry out the task they have been assigned, platform threads perform the tasks.</p><p>Whenever a supported blocking I/O call is made, the virtual thread can be unmounted from the platform thread, allowing another virtual thread to execute, and Whenever the parked thread can continue again, it’s again mounted on the same or different platform thread for execution.</p><p>There are a few cases when the virtual thread might not be unmounted in case of blocking calls:</p><ul><li>In Java 21–23, a virtual thread could remain pinned to its carrier thread while blocking inside a synchronized block or method. This limitation was removed in Java 24.</li><li>The virtual thread runs a native method or a foreign function.</li></ul><h3>Virtual Threads vs Platform Threads</h3><p>I have created this springboot project which returns the product recommendations.</p><pre>// Controller code<br>@GetMapping(&quot;/recommended-products/customer/{customerId}&quot;)<br>public List&lt;Product&gt; recommendedProducts(@PathVariable(&quot;customerId&quot;) String customerId) throws InterruptedException, ExecutionException {<br>    return productRecommendationService.recommendProducts(customerId);<br>}<br><br>// Service code<br>public List&lt;Product&gt; recommendProducts(String customerId) {<br>    List&lt;Order&gt; orders = orderService.fetchOrderHistory(customerId);<br>    Optional&lt;Customer&gt; customer = customerService.fetchCustomer(customerId);<br>    List&lt;CustomerPreference&gt; customerPreference = preferenceService.fetchCustomerPreferences(customerId);<br><br>    return customer<br>      .map(it -&gt; prepareProductRecommendation(it, customerPreference, orders))<br>      .orElse(Collections.emptyList());<br>}</pre><p>The recommendProducts method calls 3 methods internally: say fetchOrderHistory takes around 1s to return a response, fetchCustomer takes around 500 ms, and fetchCustomerPreferences takes around 400 ms. For now, these calls are just sleeping for the specified time and return response.</p><p>To test the performance of platform threads vs virtual threads, we will use jmeter to test the endpoint with 1000 users for 60 seconds:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZYBnInObPEoElSvi.png" /></figure><p>When we run using the platform thread we see below the response graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l7DxC7V95e4531RW.png" /></figure><p>Due to higher concurrent requests, the API which should have responded in 2s starts with 7s and goes to 9s and more. The response time increases because requests have to wait for an available worker thread, as the number of concurrent requests exceeds the available threads.</p><p>After enabling virtual threads in the spring boot application, I ran the same tests with the same setup, and below is the response graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*I4hNCvRc6bV2x0cg.png" /></figure><h4>The response time is what we expected and steady, isn’t it amazing, the only thing I had to do was enable virtual threads by adding spring.threads.virtual.enabled to true, which enables virtual threads. You can find the code on GitHub <a href="https://github.com/Bhavesh-Suvalaka/jvm-concurrency-examples">here </a>.</h4><p>Virtual threads don’t make individual requests faster, but they allow us to handle more concurrent requests, especially when the application is I/O intensive.</p><h3>Adoption</h3><p>Like a platform thread, a <em>virtual thread</em> is also an instance of java.lang.Thread,</p><p>there are a few ways to create it, I have shown a few of them you can explore more, <a href="https://docs.oracle.com/en/java/javase/21/core/virtual-threads.html#GUID-A0E4C745-6BC3-4DAE-87ED-E4A094D20A38">here.</a></p><ol><li>Using Thread.ofVirtual() method:</li></ol><pre>Thread vThread = Thread.ofVirtual()<br>.start(() -&gt; System.out.println(&quot;Hello World&quot;));<br><br>vThread.join();</pre><ol><li><a href="https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/concurrent/Executors.html#newVirtualThreadPerTaskExecutor()">Executors.newVirtualThreadPerTaskExecutor() </a>creates the executor service. When a task is being submitted to the executor service, it will run in the new virtual thread, it does not make any thread pool for virtual threads. try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { IntStream.range(0, 10_000).forEach(i -&gt; { executor.submit(() -&gt; { Thread.sleep(Duration.ofSeconds(1)); return i; }); }); }</li><li>Many frameworks have been adapting virtual threads so it’s worth checking out if you are using any framework. For example, After SpringBoot 3.2.x you can start using virtual threads by setting the property value spring.threads.virtual.enabled to true.</li></ol><h3>When Should You Use Java Virtual Threads?</h3><p>Virtual threads will help you to increase the throughput of an i/o intensive application, virtual threads are not faster than platform threads, they just provide a better way to manage blocking calls. In case your application is CPU intensive, virtual threads may not provide much benefit, as CPU parallelism is still limited by the available cores.</p><p>Also, you can find some other adoption guidelines in the official <a href="https://docs.oracle.com/en/java/javase/21/core/virtual-threads.html#GUID-8AEDDBE6-F783-4D77-8786-AC5A79F517C0">documentation </a>.</p><h3>Summary</h3><p>Virtual threads are a remarkable addition to Java’s concurrency history, it does not only increase the throughput of an application, It also works well with <a href="https://docs.oracle.com/en/java/javase/21/core/structured-concurrency.html#GUID-B1AAAFB8-56E1-4289-8EAF-4BF581BF28FF">Structured concurrency</a>, making concurrent tasks easier to manage. This is still a preview feature but it’s going to change the way you might think about the concurrency.</p><p>References:</p><h3>References</h3><ol><li><a href="https://openjdk.org/jeps/425">OpenJDK: JEP 425 — Virtual Threads (Preview)</a></li><li><a href="https://openjdk.org/jeps/444">OpenJDK: JEP 444 — Virtual Threads</a></li><li><a href="https://openjdk.org/jeps/491">OpenJDK: JEP 491 — Synchronize Virtual Threads without Pinning</a></li><li><a href="https://docs.oracle.com/en/java/javase/26/core/virtual-threads.html">Oracle: Virtual Threads — Implementation and Best Practices</a></li><li><a href="https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/jdk/internal/vm/Continuation.java">OpenJDK: Continuation Implementation</a></li><li><a href="https://learning.oreilly.com/library/view/modern-concurrency-in/9781098165406/">O’Reilly: Modern Concurrency in Java — A N M Bazlur Rahman</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c99b29add25" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/java-virtual-threads-a-deep-dive-into-lightweight-concurrency-4c99b29add25">Java Virtual Threads: A Deep Dive into Lightweight Concurrency</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Application Throughput: From Threads to Async and Routines]]></title>
            <link>https://medium.com/@bhavesh-suvalaka/breaking-through-bottlenecks-enhancing-throughput-with-threads-async-and-routines-711241b732b2?source=rss-557e5a5047bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/711241b732b2</guid>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[asyncio]]></category>
            <category><![CDATA[virtual-threads]]></category>
            <category><![CDATA[java-multithreading]]></category>
            <category><![CDATA[routine]]></category>
            <dc:creator><![CDATA[Bhavesh Suvalaka]]></dc:creator>
            <pubDate>Sat, 19 Sep 2026 08:07:09 GMT</pubDate>
            <atom:updated>2026-10-21T13:45:56.311Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L410WPACXWkN6cToKuNmkA.png" /><figcaption>From bottlenecks to better throughput.</figcaption></figure><h3>Introduction:</h3><p>After the internet’s evolution, the need to improve the performance of applications has increased drastically. Generally, the performance of applications is measured by two major factors:</p><ol><li>Throughput</li><li>Latency</li></ol><p>The Throughput tells the number of tasks that can be processed in a certain time, and latency describes the time taken to finish some task. In this article, we’ll try to understand how the throughput of applications, especially server applications, has improved over the years.</p><p>Applications can be categorized into two categories broadly:</p><ol><li>CPU intensive</li><li>I/O intensive</li></ol><p>As the name suggests CPU intensive heavily relies on the CPU, for example, bitcoin mining, encryption/decryption, and any application uses major arithmetic and logical calculations, whereas I/O intensive applications deal with reading and writing data to either memory, disk, caches(h/w caches) or network interfaces.</p><p>To understand how throughput has improved over the years, we also need to look at the evolution of Hardware and OS, You can find the connecting dots in this <a href="https://vipanan.sahaj.ai/blogs/276/edit">blog </a>,</p><p>Multithreading was introduced in the 1950s to achieve better performance, and as mentioned in my last blog, when we work with threads there are two beasts that we need to address:</p><ol><li>Data sharing among threads.</li><li>Maximizing CPU utilization in case of I/O intensive work.</li></ol><p>In this blog, we’ll try to address the second beast, I am going to use Java to showcase examples and also how threads have been implemented in Java.</p><h3>Server Applications</h3><p>To serve multiple requests we started to use multithreading in typical server applications, many frameworks have been developed in the last few decades which give us the flexibility to write applications in thread-per-request style, so you don’t need to worry about thread management, thread management will be taken care by application server like apache tomcat, JBoss, etc.</p><p>If you have used Spring Boot, Quarkus, or Micronaut you already know the thread per request style of writing code.</p><p>For example, in Spring Boot you might write a controller that accepts the request from the client and passes along the control to the service to perform any business logic.</p><p>For example, we can write a service that will provide product recommendations to the user based on the order history, customer preference, and some other customer data.</p><pre>public List&lt;Product&gt; recommendProducts(String customerId) {<br>  var orders = orderService.fetchOrderHistory(customerId);<br>  var customerPreference = preferenceService.fetchCustomerPreferences(customerId);<br>  var customer = customerService.fetchCustomer(customerId);<br><br>  return customer<br>          .map(it -&gt; fetchProductRecommendation(it, customerPreference, orders))<br>          .orElse(Collections.emptyList());<br><br>}</pre><p>This way of writing code is familiar, there are many benefits of this code:</p><ol><li>Easy to understand and program.</li><li>Easy to debug and profile.</li><li>The platform’s unit of concurrency is the application’s unit of concurrency.</li></ol><p>How can we increase the throughput of our application?</p><p>The scalability of server applications can be understood using Little’s Law:</p><p>Concurrent Requests = Throughput × Response Time</p><p>Say, we need to process 1,000 requests per second and each request takes 100 ms. We would need around 100 concurrent requests to achieve this throughput.</p><p>1000 requests per second is a decent throughput, but say we start getting more requests, what will happen then? To support a throughput of 10000 requests per second, either application needs to process 10000 requests per second or latency needs to be decreased. In many cases, it would be hard to decrease the latency so the only way to achieve high throughput is to support more concurrent requests. And how about 100,000 requests per second ???</p><p>But what’s the problem of supporting more concurrent requests? Let’s go back a little and understand why threads are used to maximize CPU utilization.</p><h3>Multi-threading to maximize CPU utilization</h3><p>Earlier operating systems had processes for different programs on microprocessors at once. The process is nothing but a single-threaded execution of a program. Operating systems schedule different processes and give a fair chance to execute multiple processes in parallel based on the <a href="https://en.wikipedia.org/wiki/Scheduling_(computing)">scheduling algorithm </a>.</p><p>However, context switching in processes is costly, as you need to replace the PCB of one process with another to execute the process. Multithreading came to be with the idea of sharing some part of PCB and switching context between different threads to achieve higher concurrency. So the idea is to break a program into different tasks that can be executed concurrently and assign these tasks to multiple threads to execute, so if any thread that is handling a certain task is blocked due to I/O operation, that blocking thread can be parked for the time being and the other thread is given a chance to execute. This way the OS can maximize the utilization of the CPU.</p><p>So, the throughput of an application can be increased by creating more threads to process requests concurrently. However, adding more threads doesn’t always improve throughput, as it depends on the available resources and bottlenecks.</p><h3>Limitation of threads</h3><p>Creating and terminating thread takes a certain amount of time, I tested this on my machine (Macbook Pro M1, 16GB):</p><pre>public static void main(String[] args) throws Exception {<br>  while (true) {<br>    long start = System.nanoTime();<br>    for (int i = 0; i &lt; 100_000; i++) {<br>      Thread.ofPlatform().start(() -&gt; {}).join();<br>    }<br>    long end = System.nanoTime();<br>    System.out.println((end - start) / 100_000.0);<br>  }<br>}</pre><p>Output:</p><pre>46722.06625<br><br>44911.42917<br><br>49989.89292<br><br>50572.44167<br><br>42053.68917<br><br>44844.11125<br><br>47785.11959<br><br>...</pre><p>It takes nearly 46 to 47 microseconds on average, also each thread takes some significant space as mentioned earlier. Say 1 thread takes 1 MB of stack memory by default. Theoretically, 1,000 threads would need 1 GB and 10,000 threads would need 10 GB of stack memory, also think about threads other applications might be using. And so, JVM will not allow you to create threads more than supported by the operating system. Also, context switching will be higher when you create more and more threads so even though threads are lightweight it seems it’s only lightweight when you compare with processes.</p><h3>Thread Pool</h3><p>So generally, an application server uses a thread pool, in thread pooling you create a certain amount of threads when your application starts for example Apache Tomcat creates a thread pool of 200 threads by default(This is also configurable).</p><p>So an application with a limited thread pool can only process as many blocking requests concurrently as the number of available threads. Additional requests will have to wait or be rejected.</p><p>So creating a new thread for each request is not an option when you use native or platform threads! What’s the way to achieve higher throughput, from an application perspective if you need to increase throughput you need to either scale your application horizontally or vertically. But that means more costs, isn’t there a better way to achieve higher throughput by improving the performance of the application? The answer is yes, there is: use an async style of programming.</p><h3>Asynchronous Style:</h3><p>We saw the issue with not being able to process more requests was due to the limited number of threads processing requests which are I/O intensive and most of the time are blocked for I/O operation to complete, either reading or writing.</p><p>So the new idea that arose from this situation is what if we somehow do not block these threads when they are blocked due to some i/o operations? Say a thread had made an HTTP request, which is a socket read operation essentially so until it gets the data from the internet it will be just blocked, what if during this time if same thread can handle some other requests and when the data is available we assign same or any thread to read data and continue processing from where it left! This idea gave birth to what we call a non-blocking I/O.</p><p><strong>Nonblocking I/O:</strong></p><p>As you might have guessed from the name, the idea in nonblocking i/o is not to block a thread. Or rather not to block an application thread.</p><p>An application thread makes a request for i/o and gets free immediately, it relies on the OS to handle the communication whenever data is available. Java introduced the nio stack as part of <a href="https://jcp.org/en/jsr/detail?id=51">JSR 51 </a>.</p><p>Most of the modern operating systems support I/O multiplexing. The advantage of i/o multiplexing is the application does not need to wait for i/o to complete, the application can initiate the i/o operation and rely on O/S to monitor the socket and inform the application when data is available to process again, in meantime application is free to do any other thing.</p><p>Let’s see how we can use the asynchronous style of programming to rewrite our API to get the recommended products. The previous example of recommended products depicts the sequential execution, say fetchOrder, fetchCustomerPreference and fetchCustomer are external APIs call and it takes significant time to get the response from all these three services:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/0*N-HdtxxjvpNQORAK.png" /></figure><p>One way to reduce latency is to execute all three external API calls concurrently instead of sequentially. This can also improve throughput, provided the application has enough resources to handle more requests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MelbAtjG9Zh_jNzf.png" /></figure><p>We can achieve this using CompletableFuture like so:</p><pre>public CompletableFuture&lt;List&lt;Product&gt;&gt; recommendProductsAsync(String customerId) {<br>  CompletableFuture&lt;List&lt;Order&gt;&gt; orders = orderService.fetchOrderHistoryAsync(customerId);<br>  CompletableFuture&lt;Optional&lt;Customer&gt;&gt; customer = customerService.fetchCustomerAsync(customerId);<br>  CompletableFuture&lt;List&lt;CustomerPreference&gt;&gt; customerPreference =   preferenceService.fetchCustomerPreferencesAsync(customerId);<br><br>  return CompletableFuture.allOf(orders, customerPreference, customer)<br>    .thenApplyAsync(res -&gt;<br>      toRecommendedProduct(customer.join(), customerPreference.join(), orders.join())<br>    );<br>}</pre><p>Voila! That’s done. By executing independent API calls concurrently, we can reduce latency and potentially improve throughput as well.</p><p>We have been adopting to asynchronous way of programming but at some costs:</p><ol><li>To support asynchronous programming, the Java ecosystem has to introduce asynchronous NIO in the JDK, asynchronous servlets, and many asynchronous third-party libraries, these libraries are not easy to implement or use, but it’s harder to use than thread-per-request style.</li><li>Each task given to completable future might run on the same or different threads, the debugger might not step through methods also the calls might be interleaved, so if you look at the stack trace, it might not provide usable context.</li><li>the application’s unit of concurrency is no longer the platform’s unit of concurrency.</li></ol><p>So is there any better way to achieve higher throughput and also keep the code simple enough to understand, using a thread-per-request style of code?</p><h3>Routines/fibers</h3><p>What are ways to achieve higher throughput?</p><ol><li>Either you should be able to create plentiful threads or</li><li>If you have limited threads make them unblocking</li></ol><p>We saw the cost of a non-blocking or asynchronous style of writing code. To get around this issue we again relooked at one of the oldest proposals of <a href="https://www.cs.rochester.edu/u/scott/papers/1991_SOSP_Psyche_first_class_threads.pdf">user threads </a>— the idea of creating plentiful threads in the application.</p><p>Some languages provide a lightweight thread implementation, like Erlang and Go. <a href="https://en.wikipedia.org/wiki/Fiber_(computer_science)">Routines </a>or fibers are lightweight threads that are created and managed by language or language runtime, the language runtime uses a platform thread to run the threads but scheduling is managed by language rather than os.</p><p>Java introduced Virtual Threads as a preview feature in Java 19 and made them generally available in Java 21. Virtual threads are also lightweight threads managed by Java runtime. The very initial implementation of threads in Java was based on the user threads, it was called <a href="https://en.wikipedia.org/wiki/Green_thread#:~:text=In%20computer%20programming%2C%20a%20green,underlying%20operating%20system%20(OS).">Green threads. </a>The idea here is to let the application handle the lifecycle of user threads rather than solely relying on the kernel threads. However, the green threads were replaced by the platform threads as all the green threads(user threads) were mapped to one kernel thread, so it was not able to utilize all the cores effectively.</p><p>After a few decades, the same concept has been revised but this time they have done it more efficiently, rather than using the many-to-one thread model, virtual threads support the many-to-many thread model, where multiple virtual threads m (in other languages you might find routines and fibers) are mapped to multiple kernel threads n.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KRo8YdTpYaENsqi9.png" /></figure><p>This change has enabled developers to write thread-per-request style of code without worrying about creating or managing user threads. If you are interested in understanding virtual threads you can check out this <a href="https://medium.com/@bhavesh-suvalaka/java-virtual-threads-a-deep-dive-into-lightweight-concurrency-4c99b29add25">blog</a>.</p><h3>Summary</h3><p>We saw to improve throughput how the os and languages have evolved from processes to multithreading, also asynchronous ways of programming to routines. The async and routines have improved the throughput of an application way higher so it’s worth learning both, understanding trade-offs, and adapting to these as per the need of your applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=711241b732b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How CPUs and Operating Systems Work Together: From Processes to Threads]]></title>
            <link>https://medium.com/@bhavesh-suvalaka/the-heart-of-computing-understanding-cpu-and-os-collaboration-8778b66fff26?source=rss-557e5a5047bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/8778b66fff26</guid>
            <category><![CDATA[cpu-utilization]]></category>
            <category><![CDATA[process]]></category>
            <category><![CDATA[threads]]></category>
            <dc:creator><![CDATA[Bhavesh Suvalaka]]></dc:creator>
            <pubDate>Sat, 19 Sep 2026 07:54:36 GMT</pubDate>
            <atom:updated>2026-10-21T13:45:23.063Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d1-wILTkYLXlWcLkf79ijw.png" /></figure><p>The performance of software applications depends on many factors, one of which is maximizing CPU utilization. Let’s understand the internals of the CPU first to get a better idea of how the CPU utilization has been maximized over time.</p><h3>CPU</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kZMKn7guuWxQwA2C.png" /></figure><p><em>(This image represents the simplified version of the CPU, there are more components.)</em></p><p><a href="https://en.wikipedia.org/wiki/Central_processing_unit">CPU </a>has several components working together to execute instructions. The Control Unit manages the cycles which are synchronized by the CPU clock. The cycle consists of 3 sequential components called Fetch/Decode/Execute.</p><p>The instructions which may contain data or variables are fetched from memory and placed in CPU registers, The instructions are then decoded and placed into registers again which are then executed either by CU or if any arithmetic or logical operations are neededit is given to the ALU for further execution, and it continues this process.</p><p>The performance of a computer program depends on many things, one of the factors is clock speed. The clock speed <a href="https://en.wikipedia.org/wiki/Clock_rate#:~:text=The%20first%20fully%20mechanical%20analog,of%20about%205%E2%80%9310%20Hz.">(2) </a>measures the number of cycles a CPU executes per second, and during each cycle, a plethora of transistors within the processor open and close. The first mechanical computer Z1 had a 1 Hz clock cycle and nowadays CPUs generally have GHz clock speed, the first 4-bit microprocessor- was the <a href="https://en.wikipedia.org/wiki/Intel_4004">Intel 4004 </a>. The processor had a 740 KHz to 750 KHz, nowadays computers have GHz clock rates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LAKdfosevSzLf8Qx.png" /></figure><p><em>Three clock cycles</em></p><p>If we talk about it from a programming perspective, sometimes multiple instructions are completed in a single clock cycle and it’s also possible that in some cases it takes multiple cycles to process a single instruction. This also depends on the CPU architecture which generally improves with new generations of CPUs. But I hope you got the point that a higher clock rate will typically make the CPU faster within the same generation.</p><p>In the 1960s, Moore’s Law predicted that the number of transistors on an integrated circuit would double roughly every two years, and the clock speed doubled by adding more transistors. But this stopped after 3 decades when adding more transistors started to produce more heat and adding more transistors was not yielding better results.</p><p>As increasing clock speed became difficult due to heat and power consumption, adding more cores became a better option. This allowed CPUs to execute multiple tasks in parallel, provided the application could make use of those cores.. The idea was to run more instructions in parallel on multi-cores to achieve higher performance.</p><p>The CPU executes instructions from the programs running on it. But when multiple programs need CPU time, who decides which one gets to run?</p><p>This is where the operating system comes into the picture. The OS scheduler decides which thread gets CPU time, while the CPU executes that thread’s instructions.</p><h3>Operating System</h3><p>The first generation of computers (1940–1955) was when machine language was developed for the use of computers. These computers were huge, complicated, and expensive as shown in the below image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gUcvd4TvlfvTChtq.png" /></figure><p>(From: <a href="https://www.computerhistory.org/revolution/birth-of-the-computer/4/92/365">https://www.computerhistory.org/revolution/birth-of-the-computer/4/92/365 </a>)</p><p>The way of running the program was using batch jobs, no operating system was developed at this time.</p><p>IBM’s OS/360, introduced in the 1960s, was one of the first general-purpose operating systems.</p><p>The first operating systems were developed to manage batch processing more efficiently. As computer systems became more powerful the requirement arose to execute more than one job concurrently, this led to the development of <a href="https://en.wikipedia.org/wiki/Computer_multitasking">multiprogramming </a>where jobs are kept in memory and CPU switches between these jobs to maximize CPU utilization. That’s how a <strong>process</strong> became a concept to describe<strong> a program in execution</strong>.</p><p>With the development of time-sharing operating systems, i.e., Unix and Multics, the process was refined further, and mechanics to create, schedule, and terminate processes were introduced.</p><p>Modern operating systems provide better process management, which includes process creation, inter-process communication(IPC), multiprocessing, multitasking, scheduling, termination, etc.</p><h3>Process</h3><p>A process is a program in execution, say you have many applications in your computer, stored in SSD, when you execute any of these applications it becomes a process.</p><p>Initially, the processes were the primary unit of concurrency, which means applications can be broken down into one or more processes, and the operating system takes care of running multiple processes, in a single core system multiple processes were running using time-sharing scheduling, where each process was given a specific time slice to run and thus os was doing the context switching between various processes.</p><p>In a multi-core system, it is possible to run more than one process simultaneously on multiple cores, thus achieving true parallelism, and to achieve maximum performance, the OS needs to ensure the CPU is not idle.</p><p>If Processes is CPU intensive(e.g. calculations, generating a hash function, encryption/decryption, etc) where it needs CPU to keep performing operations then it will use maximum CPU and will not sit idly. But if the processes are not given CPU-intensive work most of the time the process will end up blocked in i/o operations which is the case in many server applications. Also, process context switching is a costly operation.</p><p>The process in memory looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/0*4iAbEQXDgbpV3GHG.png" /></figure><p>(Taken from Operating System Concepts, 9th Edition)</p><p>The <strong>text</strong> section contains the program instructions, while the program counter points to the next instruction to be executed.</p><p><strong>Stack</strong> contains the process stack which includes local variables, function parameters, return address space, etc.</p><p><strong>Data</strong> contains global variables</p><p>A<strong> heap</strong> is a memory that is dynamically allocated during the execution of a process.</p><p>By default, processes have separate virtual memory spaces, including their own stack, heap, and data. However, processes can share memory using mechanisms provided by the OS, So when the CPU switches from one process to another, the OS needs to save the current process’s execution state, such as CPU registers and stack pointer, and restore the state of the next process.</p><p>This is called a context switch, and it comes with some overhead. Switching between processes may also require changing memory mappings, which can affect CPU cache and TLB performance.</p><h3>Threads:</h3><p>If you look closely at the PCB, the data, text, and heap can be shared among multiple logical tasks if the applications are broken down further and executed concurrently, only the stack and registers need to be kept separately, as they contain the context of instructions being executed.</p><p>A process starts with a single thread, but we can create multiple threads to execute different tasks concurrently. Since these threads share the same memory space, they can access the same data without needing separate copies.</p><p>However, this doesn’t mean the data will always be available in the CPU cache. Cache usage depends on how and where the threads execute.</p><p>In the case of multi-threading at any time a single core will execute one thread, To achieve better CPU utilization, the operating system will do context switching between multiple threads as threads are ready to be processed.</p><p>Then how is context switching cheaper in the case of threads? Multiple threads in a single process share the text, data, and heap so the time taken for switching context between threads is less than that required for processes. Also, the thread takes less space in memory. As you can see in the image below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9NDAY5SVYmPRFJgc.png" /></figure><p><em>(Taken from Operating System Concepts, 9th Edition)</em></p><p>Also if threads are not blocked then the OS will make sure to keep running them based on the scheduling algorithm, but what if threads most of the time are waiting for the I/O? For such cases application needs to make extra effort to handle things differently so threads can be freed, which I have discussed in this <a href="https://medium.com/@bhavesh-suvalaka/breaking-through-bottlenecks-enhancing-throughput-with-threads-async-and-routines-711241b732b2">blog</a>.</p><p>No comments yet. Select text to add a comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8778b66fff26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Message Pact with JUnit 5]]></title>
            <link>https://medium.com/techverito/message-pact-with-junit-5-5ef773594acb?source=rss-557e5a5047bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ef773594acb</guid>
            <category><![CDATA[pactflow]]></category>
            <category><![CDATA[contract-test]]></category>
            <category><![CDATA[pact-broker]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[messagepact]]></category>
            <dc:creator><![CDATA[Bhavesh Suvalaka]]></dc:creator>
            <pubDate>Sat, 30 Oct 2021 14:46:50 GMT</pubDate>
            <atom:updated>2023-06-23T09:54:17.083Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of Microservices, it’s essential to make sure that a change in one service doesn’t break anything in other services, keeping contracts in sync is important, and <strong>contract testing</strong> is a way to achieve it. There are a couple of ways to test the contract. One is to use a postman to write a contract test. One of the best options I come across is using <a href="https://docs.pact.io/pact_broker/overview">Pact</a>.</p><p>Pact provides a better way to test the contract between various consumers and producers.<a href="https://docs.pact.io/"> </a>Let’s understand this using this example.</p><p>Let’s consider that we want to add a contract test between Order service and Shipment service. Whenever a user places an order, order service will publish OrderReceivedEvent and Shipment service needs to listen to this event, in order to start the shipment of an order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g8uW4kKtuw3gDu1eYgs-Cg.png" /></figure><p>This is the basic workflow, here we’ll first add the consumer contract test for shipment service. Let’s say below is the message that the Shipment Service is listening to.</p><pre><em>data class </em>OrderReceivedEvent(<br>    <em>val </em>orderUuid: UUID,<br>    <em>val </em>products: <em>List</em>&lt;UUID&gt;,<br>    <em>val </em>paidAmount: Double,<br>    <em>val </em>purchasedBy: String,<br>    <em>val </em>purchasedDate: LocalDate<br>)</pre><p>We want to make sure, order service is publishing the correct message as above, so we’ll add Consumer like so</p><pre>@ExtendWith(PactConsumerTestExt::<em>class</em>)<br>@PactTestFor(providerName = &quot;order-service&quot;, port = &quot;8080&quot;, providerType = ProviderType.<em>ASYNCH</em>)<br><em>class </em>PactConsumer {<br><br>    @Pact(consumer = &quot;shipment-service&quot;)<br>    <em>fun </em>validOrderReceivedEvent(builder: MessagePactBuilder): MessagePact {<br>        <em>val </em>body = expectedBodyForOrderReceivedEvent()<br>        <em>return </em>builder.expectsToReceive(&quot;OrderReceivedEvent&quot;).withContent(body).toPact()<br>    }<br><br>    @Test<br>    @PactTestFor(pactMethod = &quot;validOrderReceivedEvent&quot;)<br>    <em>fun </em>`test validOrderReceivedEvent`(messages: <em>List</em>&lt;Message&gt;) {<br>        Assertions.assertNotEquals(messages.size, 0)<br>        validateMessage(messages[0], OrderReceivedEvent::<em>class</em>.<em>java</em>)<br>    }<br><br>    <em>private fun </em>&lt;T&gt; validateMessage(message: Message, t: Class&lt;T&gt;) {<br>        <em>val </em>mapper = ObjectMapper().<em>registerKotlinModule</em>()<br>        <em>val </em>messageObj = mapper.readValue(<em>String</em>(message.contentsAsBytes()), t)<br>        Assertions.assertNotNull(messageObj)<br>    }<br><br>    <em>private fun </em>expectedBodyForOrderReceivedEvent(): DslPart =<br>        <em>newJsonObject </em><strong>{<br>            </strong><em>this</em>.uuid(&quot;orderUuid&quot;)<br>                .array(&quot;products&quot;, <em>Consumer </em><strong>{ it</strong>.uuid() <strong>}</strong>)<br>                .numberType(&quot;paidAmount&quot;)<br>                .stringType(&quot;purchasedBy&quot;)<br>                .datetime(&quot;purchasedDate&quot;)<br>        <strong>}<br></strong>}</pre><p>Here PactConsumerTestExt is used to run the pact consumer test, the method annotated with@Pact mentions the consumer service name, this method returns the pact that needs to be validated. Also the @Test case has been added to make sure that the pact message that we want to validate contains a valid contract.</p><p>Once you run this pact consumer test, it will create the consumer contract at @Target/pact folder. You can configure your pipeline to<strong> publish this PactConsumer contract to Pact Broker.</strong></p><p>Once the contract is published to Pact Broker, it’s essential to check the changes on the consumer side will not fail if it’s been merged to the master branch and to check that you can add the <a href="https://docs.pact.io/pact_broker/can_i_deploy/"><strong>can-i-deploy</strong> </a>check to your pipeline.</p><p>Now let’s look at the provider side of this.</p><p>Provider side, we want to verify that OrderReceivedEvent is compliant with the Shipment Service. Any changes in the contract doesn’t break anything at the consumer side. To verify that, we can add the PactVerify test, like so:</p><pre>@Provider(&quot;order-service&quot;)<br><em>//@PactBroker(url = &quot;brokerUrl&quot;)<br></em>@PactFolder(&quot;src/test/resources&quot;)<br><em>class </em>PactProvider {<br><br>    @TestTarget<br>    <em>private val </em>target = MessageTestTarget()<br><br>    @BeforeEach<br>    <em>fun </em>before(context: PactVerificationContext) {<br>        context.target = target<br>    }<br><br>    @TestTemplate<br>    @ExtendWith(PactVerificationInvocationContextProvider::<em>class</em>)<br>    <em>fun </em>pactVerificationTestTemplate(context: PactVerificationContext) {<br>        context.verifyInteraction()<br>    }<br><br>    @PactVerifyProvider(&quot;OrderReceivedEvent&quot;)<br>    <em>fun </em>verifyOrderReceivedEvent(): String? {<br>        <em>val </em>df = SimpleDateFormat(&quot;yyyy-MM-dd&quot;)<br>        <em>val </em>objectMapper = ObjectMapper().findAndRegisterModules()<br>        objectMapper.<em>dateFormat </em>= df<br>        <em>return </em>objectMapper.writeValueAsString(<em>anOrderReceivedEvent</em>)<br>    }<br>}</pre><p>Here I have kept the pact contract which consumer has generated at test/resources folder to test the pact between two parties, but if you are using the pact broker, (and that’s what should be used), you can mention the URL of the pact broker and remove the @PactFolder annotation, in that case test will fetch the contract from the broker and verify the changes against it.</p><p>You can set up this test to run as part of the separate pipeline which will be triggered by the <a href="https://docs.pact.io/pact_broker/webhooks/">webhook</a>s.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ef773594acb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/techverito/message-pact-with-junit-5-5ef773594acb">Message Pact with JUnit 5</a> was originally published in <a href="https://medium.com/techverito">TechVerito</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>