<?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 Mehrbod Khiabani on Medium]]></title>
        <description><![CDATA[Stories by Mehrbod Khiabani on Medium]]></description>
        <link>https://medium.com/@mehrbod.kh?source=rss-3546c7580781------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cxQJMjmtXqwswl52_hoLPg.jpeg</url>
            <title>Stories by Mehrbod Khiabani on Medium</title>
            <link>https://medium.com/@mehrbod.kh?source=rss-3546c7580781------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 12:25:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mehrbod.kh/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[Kotlin Coroutines vs Virtual Threads — Part 1: Performance]]></title>
            <link>https://medium.com/@mehrbod.kh/kotlin-coroutines-vs-virtual-threads-part-1-performance-0e09dcb489a3?source=rss-3546c7580781------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e09dcb489a3</guid>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[virtual-threads]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Mehrbod Khiabani]]></dc:creator>
            <pubDate>Wed, 24 Sep 2025 19:22:52 GMT</pubDate>
            <atom:updated>2025-09-24T19:22:52.700Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kotlin Coroutines vs Virtual Threads — Part 1: Performance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WKFDDLU4EeHSxwIzp8weWA.png" /></figure><p>We’ve been hearing a lot about these two technologies lately. Java, from version 21, finally added a native, non-blocking solution for long running blocking IO operations, and spoilers, it’s really, really good. Not only because it’s trying to provide a quick and clean solution, but also if you’re already familiar with Java’s multi-threading, it fits right in. <br>In this series, I’m going to compare these two tools, understand their differences, and try to get a better understanding of these two solutions. <br>If you’re a Kotlin developer, and trying to choose between one of these two technologies, then this is the post for you, and if you’re a Java developer, maybe it’s time to switch to Kotlin?<br>We are going to take a look at different aspects of each technology: performance, capabilities, ease of use and support in this series, and we’re starting with performance.</p><h3>Context</h3><p>Although, these two technologies are trying to solve a set of different problems, in core of both solutions, lies the need for a refined <strong>Non-blocking</strong> programing solution.</p><p>During the runtime lifecycle of our programs, regardless of whether they are a backend application, frontend, mobile, etc…, there are times which our threads wait for some other stuff to happen. They wait for an API call to finish, for a database transaction to be completed, for a calculation to be finalized, for an upload to happen. What we, as engineers, have to strive for, is not to block our threads while waiting for these stuff to happen, and free them up so they can handle other tasks. This simple idea, will result it performance gains for our programs, and will reduce the time that our threads stay in idle state, reducing starvation, and a lot of other benefits. <br>However, writing non-blocking programs was always a challenge. There are so many different solutions for this problem, and in this series, we’re going to discuss the main one in Kotlin (Coroutines) and its counter part in Java, which of course can be used in Kotlin as well, virtual threads.</p><h3>Performance</h3><p>I am going to start off this comparison with performance. After all, these solutions are there to ensure a performant application, and good use of resources of our systems.</p><p>I need to mention something first, the performance comparison is going to be highly simulated and in lab conditions. As much as I’m trying to provide a real world example, but a lot of different factors might be playing a role in the final result, thus, I’m going to stick to a simple program, running 2 million concurrent runs of a simple simulated API request, and then running a simple synchronized calculation.</p><p>Let’s jump into the code:</p><p>First, let’s introduce an interface, which includes a runTest() method, and I expect this method to run the test, and measure the time for how long it will take. It also includes the constants the we defined earlier.</p><pre>interface NonBlockingTest {<br>    // Runs the test, and measures how long the test took in ms<br>    fun runTest() {<br>        measureTime { test() }<br>    }<br><br>    fun test()<br><br>    companion object {<br>        // Simulated API call delay<br>        const val API_DELAY = 200L<br>        // Number of concurrent tasks running<br>        const val CONCURRENT_TASKS = 2_000_000<br>    }<br>}</pre><p>Now, let’s get to implementation of this interface in two different versions:<br>1. Using Kotlin Coroutines<br>2. Using Virtual Threads in Kotlin</p><p>First, the Kotlin Coroutines version:</p><pre>import com.mehrbod.NonBlockingTest.Companion.API_DELAY<br>import com.mehrbod.NonBlockingTest.Companion.CONCURRENT_TASKS<br>import kotlinx.coroutines.CoroutineScope<br>import kotlinx.coroutines.Dispatchers<br>import kotlinx.coroutines.delay<br>import kotlinx.coroutines.joinAll<br>import kotlinx.coroutines.launch<br>import kotlinx.coroutines.runBlocking<br><br>class CoroutineNonBlockingTest : NonBlockingTest {<br>    private val scope = CoroutineScope(Dispatchers.IO)<br>    private var counter = 0<br><br>    override fun test() {<br>        runBlocking {<br>            List(CONCURRENT_TASKS) {<br>                scope.launch {<br>                    // Simulating API call<br>                    delay(API_DELAY)<br>                    // Simulating some light calculations<br>                    repeat(100) {<br>                        synchronized(this) {<br>                            counter++<br>                            counter--<br>                        }<br>                    }<br>                }<br>            }.joinAll()<br>        }<br>    }<br>}</pre><p>Then, the Kotlin version of Virtual Threads:</p><pre>import com.mehrbod.NonBlockingTest.Companion.API_DELAY<br>import com.mehrbod.NonBlockingTest.Companion.CONCURRENT_TASKS<br>import java.util.concurrent.Executors<br><br>class VirtualThreadNonBlockingTest : NonBlockingTest {<br>    private val executorService = Executors.newVirtualThreadPerTaskExecutor()<br>    private var counter = 0<br><br>    override fun test() {<br>        List(CONCURRENT_TASKS) {<br>            executorService.submit {<br>                // Simulating API call<br>                Thread.sleep(API_DELAY)<br>                // Simulating some light calculations<br>                repeat(100) {<br>                    synchronized(this) {<br>                        counter++<br>                        counter--<br>                    }<br>                }<br>            }<br>        }.forEach { it.get() }<br>    }<br>}</pre><p>And just for the sake of completion, here’s the implementation of measureTime function:</p><pre>inline fun NonBlockingTest.measureTime(block: () -&gt; Unit) {<br>    val startTime = System.currentTimeMillis()<br>    block()<br>    val endTime = System.currentTimeMillis()<br>    println(&quot;${this.javaClass.simpleName} took ${endTime - startTime}ms&quot;)<br>}</pre><p>Now that we have our basic tests ready, it’s time to take a look at the results, on some of the different CPUs that I had access to:</p><p>5800X with 32GB of RAM:</p><pre>CoroutineNonBlockingTest took 6513ms<br>VirtualThreadNonBlockingTest took 17166ms</pre><p>M1 Pro with 64GB of RAM:</p><pre>CoroutineNonBlockingTest took 27439ms<br>VirtualThreadNonBlockingTest took 56122ms</pre><p>Seems like, at least in this test case, and on these specific hardwares, Kotlin Coroutines have the advantage in performance, by quite a tangible amount.</p><h3>Why this huge gap in performance?</h3><p>The underlying differences in both technologies lead to this difference in performance. These are the main ones:</p><ul><li>Virtual threads, are still Thread objects, thus needing a stack (though it is being stored in head this time around), but Coroutines just keep the minimum amount of variables needed for resume .</li><li>Virtual threads have to do a costly <strong>stack snapshot</strong> operation, but resumption is just a function call on Coroutines.</li><li>Virtual threads use normally around a few KBs per thread for stack, but its around hundreds of bytes on Coroutines, depending on the variables.</li><li>Context switching is also quicker with coroutines. It’s around 100 nanoseconds for virtual threads, but around tens of nano seconds for Coroutines.</li></ul><p>All of these will result in this performance difference between coroutines and Virtual Threads.</p><h3>That is not the entire story</h3><p>As you might have noticed, I used Dispatchers.IO coroutine dispatcher for doing these tests. The reason for this, instead of other types of dispatchers, is that the main reason for existence of virtual threads, is to resolve the blocked state of threads during long running IO operations. To be comparing both fairly, Dispatchers.IO seems to best dispatcher to be used for this comparison.</p><blockquote>Virtual threads are suitable for running tasks that spend most of the time blocked, often waiting for I/O operations to complete. However, they aren’t intended for long-running CPU-intensive operations.</blockquote><p>I ran this experiment on an AMD 5800X CPU, which has 16 platform threads. This is a favorable scenario for coroutines, and doesn’t take one major factor in consideration: Dispatchers.IO context, in its default form, will at most run on a maximum of 64platform threads, and if you compare it with the number 256 which is the number of platform threads that virtual threads can run on, it means there’s a vertical scaling disadvantage for coroutines, if the running server has more than 64 threads.</p><p>But worry not, thankfully, we can use the virtual threads as coroutine dispatcher, meaning it will underlyingly use virtual threads to run the long running IO operations, and our code will be able to use all 256 platform threads.</p><p>To do it, you can write a code like this:</p><pre>val Dispatchers.VirtaulThreads<br>        get() = Executors.newVirtualThreadPerTaskExecutor().asCoroutineDispatcher()<br>    <br>val scope = CoroutineScope(Dispatchers.VirtaulThreads)</pre><p>I unfortunately don’t have access to a high thread count PC to be able to test the performance, however, there’s something that we have to pay attention to, using virtual threads in combination with coroutines, will add the overhead of both solution, and might even decrease the performance, unless its absolutely limited by the number of platform threads that it can run on.</p><h3>Conclusion</h3><p>We have compared virtual threads and coroutines only from performance perspective, trying to cover some of the corner cases as well, only in blocking IO operations. <br>In these tests, it looks like coroutines have the advantage in performance, and can even scale better with virtual threads. However, take all of these with a grain of salt, as there might be cases which this lab type test won’t be a representative state.</p><p>But there are more to choosing between these two technologies, such as ease of use and API design, migration, features, etc… which I intend to cover in the future posts. Stay tuned.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e09dcb489a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migration to Compose, from a ViewModel standpoint]]></title>
            <link>https://medium.com/ridedott/migration-to-compose-from-a-viewmodel-standpoint-29f7d08c7786?source=rss-3546c7580781------2</link>
            <guid isPermaLink="false">https://medium.com/p/29f7d08c7786</guid>
            <category><![CDATA[compose]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[viewmodel]]></category>
            <dc:creator><![CDATA[Mehrbod Khiabani]]></dc:creator>
            <pubDate>Mon, 27 Jun 2022 21:48:10 GMT</pubDate>
            <atom:updated>2022-06-27T21:48:10.954Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WVUBQsNgePqQxmrHjaID4g.png" /><figcaption>Image from <a href="https://android-developers.googleblog.com/2021/07/jetpack-compose-announcement.html">https://android-developers.googleblog.com/2021/07/jetpack-compose-announcement.html</a></figcaption></figure><p>Our trust grew more and more with Jetpack Compose, as we saw how it can improve UI implementation. It was faster, easier, and less error prone to develop our UI with it. So, a while after it became stable, we decided to migrate to Compose in our Spott app. But, like everything, it came with its own challenges. In this post, I’m gonna talk about some of the challenges that we had to overcome and how we did it.</p><p>Without further ado, let’s get to it:</p><h3>Performance monitoring</h3><p>If you’re just starting to migrate your application to compose, you should keep in mind that the UI performance visible in your app when your testing a debug version, is not the final performance of the app, and it’s more pronounced when you’re using compose.</p><p>Sometimes, lists might look laggy, bottom sheets might open late and other visual performance problems that might make you reconsider using views instead, but they all might only happen when you’re running the debug version of your app.</p><p>For more information, you can check <a href="https://medium.com/androiddevelopers/why-should-you-always-test-compose-performance-in-release-4168dd0f2c71/">here</a>.</p><h3>Combining ViewModels with StateHolders can be a life saver</h3><p>At first, as we already had ViewModel s in place, we wanted to store all UI states inside the ViewModel . This meant that we had to add some new states that we didn’t need to add before migrating to compose. For example, we now had to store the currently selected radio button value, currently written text inside text fields, currently selected items, etc. as opposed to only sending them once the user clicks on the Apply button. This meant that we had to add a lot of new states to our current ViewModel s, in addition to changing how the APIs for the ViewModel s work. For example, we didn’t need to get any info from UI when user clicked on Apply button.</p><p>But after a while and facing different situations where we unnecessarily had to break down our UI state, we actually tried to implement <a href="https://developer.android.com/jetpack/compose/state#viewmodel-state">this</a> (example included) section of Compose state management, and in a lot of cases, it made our lives a lot easier by removing UI elements’ state from ViewModel s.</p><blockquote>Because state holders are compoundable and ViewModels and plain state holders have different responsibilities, <strong>it’s possible for a screen-level composable to have both</strong> a ViewModel that provides access to business logic <em>AND</em> a state holder that manages its UI logic and UI elements’ state. Since ViewModels have a longer lifespan than state holders, state holders can take ViewModels as a dependency if needed.</blockquote><h3><strong>Handling one-off events</strong></h3><p>This issue, is not directly related to compose itself, but been made a lot more visible when migrating to compose. There’s a great blog post on this subject by <a href="https://medium.com/u/3b5622dd813c">Manuel Vivo</a> which you can find <a href="https://medium.com/androiddevelopers/viewmodel-one-off-event-antipatterns-16a1da869b95">here</a>. But in a nutshell:</p><blockquote>You should handle ViewModel events immediately, causing a UI state update. Trying to expose events as an object using other reactive solutions such as Channel or SharedFlow doesn’t guarantee the delivery and processing of the events.</blockquote><h3>Don’t forget about Combine</h3><p>Though this is not directly related to compose itself, but is one of the things that helped us migrate to compose more easily.</p><p>For context, our ViewModel s looked like this before migrating to compose:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae44d40e75bb4d858ee1f793b62f0f9b/href">https://medium.com/media/ae44d40e75bb4d858ee1f793b62f0f9b/href</a></iframe><p>As apparent, instead of a single UI state, we had multiple streams trying to publish the UI info. So, we wanted to reduce it to only one UI state which contained all related UI info. So first, we created the UI state data class :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c043c016135112869b1f6007e502936/href">https://medium.com/media/5c043c016135112869b1f6007e502936/href</a></iframe><p>One way of doing it is using update function of MutableStateFlow and adding it wherever one of the UI info changes. Although pretty straight forward, but it requires you to change the ViewModel and adds to the overall time of migration and review process.</p><p>Another way is to use combine function to combine multiple StateFlow s and create the UI state accordingly:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c5f2ecda09e281fa9725459d6e3f299/href">https://medium.com/media/8c5f2ecda09e281fa9725459d6e3f299/href</a></iframe><p>This way, with minimal changes to the ViewModel , you can easily reduce your events and states into one UI state.</p><h3>Extension properties can be powerful</h3><p>Some UI state fields can be related to each other. For example, we wanted a button to be enabled only when there is a radio button selected and the screen is not in a loading state. Without extension properties, it can look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff393b8e3430dba7113eb84d499ac37a/href">https://medium.com/media/ff393b8e3430dba7113eb84d499ac37a/href</a></iframe><p>But using extension properties, it can look a lot better and easier to manage:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b0f421a8a91223edbd9b88ec15538d9/href">https://medium.com/media/5b0f421a8a91223edbd9b88ec15538d9/href</a></iframe><p>Now, you don’t need to explicitly change the state of button or worry about it carrying the wrong state.</p><h3>SingleLiveData for events</h3><p>Though already mentioned, view model events should be reduced to UI state, and then updated via UI events. But we found that sometimes, it’s not a good idea to go that route because of some API issues. For example, we wanted to display a Toast , and understanding when Toast is finished displaying can be a bit messy. I’m using Toast as an example as it can happen for some other, specially older libraries and APIs.</p><p>If we wanted to implement it using UI states only, our code would probably looked like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fea409cfbde5f82aee8bb0264c3ac919/href">https://medium.com/media/fea409cfbde5f82aee8bb0264c3ac919/href</a></iframe><p>Though it’s not a lot of work, but it makes you think about some corner cases like LifeCycle as the API doesn’t support it. If we wanted to do this using SingleLiveEvent in this case, the changes would’ve looked like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/381a533e26ffda213448f15fcb73549f/href">https://medium.com/media/381a533e26ffda213448f15fcb73549f/href</a></iframe><p>It’s a bit more minimal, and it works well enough for this use case. But be caution about using it, as the general practice for it is reducing the events to UI state, and it only should be done when the other options are not that straight forward.</p><h3>Don’t forget rememberUpdatedState</h3><p>One of the issues that I constantly ran into, was forgetting about using rememberUpdatedState as everything worked well enough for me not to pay attention to it. But none the less, it should be there. If you’re interested in learning when to use it, you can check <a href="https://developer.android.com/jetpack/compose/side-effects#rememberupdatedstate">here</a>.</p><h3>Conclusion</h3><p>Overall, migrating to Jetpack Compose was more straight forward than we thought. It helped us write cleaner UI related codes, develop faster, and manage our states easier. But it still has some of its own corner cases, which should be considered when migrating.</p><p>In the end, I want to mention that if you’re more curious about how to implement using Compose, or how to break down UI states, I strongly recommend that you take a look into <a href="https://github.com/android/nowinandroid">Now in Android</a> project which contains a lot of best practices and can play as a good sample project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29f7d08c7786" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ridedott/migration-to-compose-from-a-viewmodel-standpoint-29f7d08c7786">Migration to Compose, from a ViewModel standpoint</a> was originally published in <a href="https://medium.com/ridedott">Dott</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>