<?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 sridhar subramaniam on Medium]]></title>
        <description><![CDATA[Stories by sridhar subramaniam on Medium]]></description>
        <link>https://medium.com/@sridhar-sp?source=rss-8b095914072e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*drhV8cvKkMixkLAoKQissQ.jpeg</url>
            <title>Stories by sridhar subramaniam on Medium</title>
            <link>https://medium.com/@sridhar-sp?source=rss-8b095914072e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 12:32:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sridhar-sp/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[From Single Core to Coroutines]]></title>
            <link>https://medium.com/@sridhar-sp/from-single-core-to-coroutines-b70506794a6b?source=rss-8b095914072e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b70506794a6b</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[multithreading]]></category>
            <dc:creator><![CDATA[sridhar subramaniam]]></dc:creator>
            <pubDate>Sat, 04 Jul 2026 15:51:38 GMT</pubDate>
            <atom:updated>2026-07-04T15:51:53.067Z</atom:updated>
            <content:encoded><![CDATA[<p>Exploring Threads, Processes, and the Rise of Coroutines (Part 5)</p><blockquote>In the <a href="https://medium.com/@sridhar-sp/from-single-core-to-coroutines-46faa1f692ee">previous blog</a>, we introduced coroutines as a concurrency primitive that enables cooperative multitasking at the application layer. We saw how blocking IO ties a thread for the entire duration of the IO operation and how non-blocking IO using Java NIO allows the thread to be freed up while waiting for the IO to complete. We also saw that coroutines do not automatically make blocking code non-blocking, and a valid suspension point must be explicitly introduced in the code. In this blog we will explore <strong>what exactly makes a function suspending</strong> and how Kotlin implements <strong>suspension under the hood</strong>. And also, what is callback hell, <strong>Continuation Passing Style (CPS).</strong></blockquote><h4>What Exactly Makes a Function Suspending?</h4><p>In a previous blog, we discussed that <a href="https://en.wikipedia.org/wiki/Coroutine">coroutine</a> is a concurrency primitive that enables <strong>cooperative multitasking</strong>. The name coroutine reflects this principle. A routine means a regular function, and a coroutine means a <br><strong>co-operative</strong> routine. It will co-operate with other coroutines to execute routines effectively and fairly.</p><p><strong>How Do We Co-Operate with Other Coroutines?</strong></p><p>First, what do we mean by &#39;<strong>co-operate&#39;</strong> in terms of functions? It means allowing other functions to execute fairly so all functions get a chance to execute.</p><p><strong>How do we do this?</strong> One way is to yield the control of execution. Who better knows when to yield a function&#39;s execution than the function itself. A function can decide when it no longer needs the CPU and <strong>yield</strong>, allowing other coroutines to run. In a similar way, other functions yield control, and this function, which was yielded earlier, may get a chance to execute again.</p><p><strong>Let&#39;s see an example below</strong></p><p>Assume we have a heavy CPU-intensive task to run. Since it’s CPU-intensive, it will consume <strong>100%</strong> of the <strong>thread</strong> it runs on during execution. If a single function itself consumes <strong>100% of the </strong>thread, it may not be fair to others, and other functions may not get a chance to execute, making them appear to hang. A coroutine can avoid this by deciding when to voluntarily yield, allowing others to run in the meantime (i.e., <strong>cooperating</strong> with each other).</p><p>The below example is a CPU-intensive task which doesn’t yield. If this gets executed till this program finishes execution, no other function can run in a single-thread environment</p><pre>fun heavyComputation(): Long {<br>    println(&quot;[${Thread.currentThread().name}] Heavy computation started&quot;)<br>    var result = 0L<br>    for (i in 0 until 100_000_000) {<br>        result += sqrt(i.toDouble()).toLong()<br>    }<br>    println(&quot;[${Thread.currentThread().name}] Heavy computation completed, result: $result&quot;)<br>    return result<br>}</pre><p>Let’s rewrite <strong>heavyComputation</strong> as a suspending, cooperative function by calling yield() every 1 million iterations. Since <strong>yield()</strong> is itself a <strong>suspend</strong> function, we mark <strong>heavyComputation</strong> as suspend as well.</p><pre>suspend fun heavyComputation(): Long {<br>    println(&quot;[${Thread.currentThread().name}] Heavy computation started&quot;)<br>    var result = 0L<br>    for (i in 0 until 100_000_000) {<br>        result += sqrt(i.toDouble()).toLong()<br>        if (i % 1_000_000 == 0) {<br>            println(&quot;[${Thread.currentThread().name}] Yielding at iteration $i&quot;)<br>            yield() // application layer voluntarily gives up control every 1 million iteration<br>        }<br>    }<br>    println(&quot;[${Thread.currentThread().name}] Heavy computation completed, result: $result&quot;)<br>    return result<br>}</pre><p>To prove that yielding is working, we launch another coroutine that prints ‘<strong>Doing other work</strong>’ <strong>5 times</strong> at <strong>50ms</strong> <strong>intervals</strong>. We deliberately limit the dispatcher to a single thread using limitedParallelism(1)so both coroutines share the same thread, making the cooperative scheduling effect clearly visible in the output.</p><pre>suspend fun otherWorks() {<br>    repeat(5) {<br>        delay(50.milliseconds)<br>        println(&quot;[${Thread.currentThread().name}] Doing other work&quot;)<br>    }<br>    println(&quot;[${Thread.currentThread().name}] Other works are completed&quot;)<br>}<br><br>suspend fun main() {<br><br>    val defaultScope = CoroutineScope(Dispatchers.Default.limitedParallelism(1))<br><br>    val job1 = defaultScope.launch {<br>        heavyComputation()<br>    }<br>    val job2 = defaultScope.launch {<br>        otherWorks()<br>    }<br><br>    listOf(job1, job2).joinAll()<br><br>    println(&quot;Main execution done&quot;)<br>}</pre><p>Let’s see the results. The comparison table below shows the output for both cases. In the first column, the function yields control periodically, allowing other coroutines to step in and execute when needed both coroutines share the thread fairly. In the second column, the function never yields, causing it to run to completion before any other coroutine gets a chance to use the thread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*31aFsO55KerP1RYknpurSQ.png" /><figcaption>Results when using yield vs not using it</figcaption></figure><h4>So All Suspend Functions Should Be Created with Yield?</h4><p>Not always; sometimes yielding happens <strong>implicitly</strong>. As we saw in the <a href="https://medium.com/@sridhar-sp/from-single-core-to-coroutines-46faa1f692ee">previous blog</a>, when we initiated a non-blocking file read using Java NIO, the coroutine suspended at the suspendCoroutine call, freeing the thread while the read operation was handled internally by the NIO framework. Once the read completed, the callback resumed the coroutine. The thread was never blocked; the work was simply handed off. In cases like this, we can use suspendCoroutine or suspendCancellableCoroutine to bridge callback-based async APIs into suspend functions.</p><p>So far we have discussed <strong>yield</strong>, <strong>fair execution</strong>, and <strong>cooperative multitasking </strong>and throughout all of this, we keep encountering the suspend keyword. Let&#39;s deep dive into what it really means.</p><h3>What is a suspend function?</h3><p>suspend is a modifier in Kotlin. When added to a function, it signals to the compiler that this function <strong>can suspend execution</strong> without blocking the underlying thread and resume at a later point in time. The <strong>compiler</strong> then <strong>transforms</strong> the <strong>suspend</strong> function using <strong>Continuation Passing Style (CPS)</strong>, building a state machine where each suspension point becomes a distinct state and allowing the coroutine runtime to save progress, free the thread, and resume execution later exactly where it left off.</p><h4>Rules of a Suspend Function</h4><p><strong>1. A suspend function should never block the underlying thread</strong></p><p>This is the most important contract of a suspend function. Any code that blocks the underlying thread, such as Thread.sleep() or a blocking IO call, should not be placed inside a suspend function without wrapping it in an appropriate dispatcher context. <strong>By definition, a suspend function suspends execution without blocking the thread, and it is the responsibility of the author to uphold this contract.</strong></p><p>Even if this rule is violated, the Kotlin compiler will still generate the state machine code using CPS without any error. However, the consumer of the suspend function will have no way of knowing that the thread is being blocked unless they dig into the implementation.</p><p><strong>2. The author should define the appropriate dispatcher inside the suspend function</strong></p><p>Only the author of the suspend function knows which dispatcher is best suited for the operation. The author should use <strong>withContext</strong> with the appropriate dispatcher internally, making the function <strong>main-safe</strong>, safe to call from any dispatcher without the consumer needing to worry about thread management.</p><p>The consumer’s only responsibility is to create the scope and manage the lifecycle of the coroutine. Assume we have a readFile suspend function the consumer might be tempted to use Dispatchers.IO. But as per rule 1, the suspend function should not block the thread, which means the consumer can even use the coroutine scope created using it Dispatchers.Main and not worry that it will block the main thread. Hence, the author of the suspend function should use an appropriate dispatcher internally.</p><h3><strong>Use of a suspend function?</strong></h3><p>In the world of asynchronous programming (i.e., instead of getting the result immediately, we receive it after some time), we deal with callbacks. If one async function requires the output of another async function, we end up chaining function calls in a nested manner, which not only breaks code readability but also makes error handling cumbersome.</p><p>Let’s consider below example for our use case.</p><pre>fun main() {<br><br>    // getToken or getUser may fail, <br>    // - exactly communicating which one failed to caller requires extra effort.<br>    getToken(onResult = { token -&gt;<br>        // if getToken failed, <br>        // - then retrying getToken is not easy, makes the code harder to read<br>        getUser(token, onResult = { user -&gt;<br>            println(&quot;Main Output : $user&quot;)<br>            // more function like getAddress or getPhone etc will be nested<br>        })<br>    })<br><br>}</pre><p>We have getToken and getUser, both asynchronous methods that return either a result or an error through an onResult callback. The token received from the getToken function is passed as an input to getUser.</p><p>We can already see that with only one nested function, the code becomes <strong>harder to read</strong>. On top of that, it is <strong>difficult</strong> to <strong>propagate errors </strong>back to the caller and identify whether the error occurred in getToken or getUser. Also, if getToken fails and we want to <strong>retry</strong> that function, there is <strong>no easy way to do so;</strong> we would need to add several extra lines to implement a retry mechanism.</p><p>Callbacks solve the problem of executing asynchronous work, but they introduce the above challenges. Instead of writing code in a top-to-bottom manner, we are forced to describe <strong>what should happen next</strong> inside another function.</p><p>What we really want is:</p><ul><li>Write asynchronous code in a <strong>sequential and readable</strong> way.</li><li>Handle errors in a <strong>centralized/structured</strong> manner.</li><li>Easy retry operations.</li></ul><p>To address these limitations, we can make use of <strong>coroutines</strong>.</p><p>Of course, even <strong>without coroutines</strong>, asynchronous code can be handled using Java’s <strong>Future</strong>. However, <strong>Future</strong> comes with its own limitations. It allows us to represent a value that will be available in the future, <strong>but it does not provide an easy way to compose multiple asynchronous operations </strong>or handle errors cleanly. In <strong>many cases</strong>, <strong>we end up blocking</strong> the thread while waiting for the result (i.e., by calling Future.get()), which <strong>defeats</strong> the <strong>purpose</strong> of <strong>asynchronous or concurrent programming</strong>.</p><p>Because of these shortcomings, we need a better abstraction, one that keeps asynchronous code <strong>readable</strong>, <strong><em>non-blocking</em></strong>, and easy to reason about.</p><p>This is where <strong>coroutines</strong> come into the picture.</p><p>Coroutines allow us to write asynchronous code in a sequential style while the underlying execution remains non-blocking. Instead of nesting callbacks or manually managing futures, we can express async logic as if it were normal synchronous code.</p><p>Let’s see how this improves our previous example.</p><pre>private val client = HttpClient(CIO)<br><br>suspend fun printUser() {<br>    val token = getToken() // asynchronous call; call suspend till we get result (token)<br>    val user = getUser(token)<br>    println(&quot;Main Output : $user&quot;)<br>}<br><br>suspend fun getUser(token: String): String {<br>    val user = dummyNetworkCall(input = token.hashCode().toString())<br>    return user<br>}<br><br>suspend fun getToken(): String {<br>    val token = dummyNetworkCall(input = &quot;token&quot;)<br>    return token<br>}<br><br>private suspend fun dummyNetworkCall(input: String): String {<br>    val response = client.get(&quot;https://jsonplaceholder.typicode.com/todos/1&quot;)<br>    return input + response.bodyAsText()<br>}</pre><p>The getToken and getUser turned into suspend functions thanks to dummyNetworkCall, which itself is a suspend function that provides <strong>non-blocking IO</strong>. The dummyNetworkCall will perform a network call and return the future result as if it were returning from a synchronous method.</p><p>At first it will look like synchronous code and nothing related to non-blocking IO. But under the hood, the Ktor client get function uses suspendCoroutineUninterceptedOrReturn which takes a callback argument called <strong>continuation</strong> and uses that object to return the response.</p><blockquote>A coroutine does not magically turn a blocking call into a non-blocking one, we explained this in the <a href="https://medium.com/@sridhar-sp/from-single-core-to-coroutines-46faa1f692ee">previous blog</a> using a real blocking IO example.</blockquote><p>But where is the callback code? The Kotlin compiler generates it automatically, <strong>transforming</strong> the <strong>sequential-looking suspend function into a state machine</strong> using <strong>Continuation Passing Style (CPS)</strong>.</p><h3>What Is Continuation Passing Style (CPS)</h3><p><strong>CPS</strong> is a style of programming where a function does not return its result directly to the caller. Instead, it takes an extra argument, a <strong>continuation </strong>which is a <strong>callback</strong> that gets invoked with the computed result once the function completes.</p><p>In Kotlin, the compiler applies <strong>CPS</strong> transformation to every suspend function under the hood, adding an implicit Continuation parameter at the end of the method signature and converting the sequential-looking code into a state machine where each suspension point becomes a distinct state.</p><p>Consider the below function as an example. ThedummyNetworkCall is a suspend function which makes use ktor client to call a REST API.</p><pre>private val client = HttpClient(CIO)<br><br>private suspend fun dummyNetworkCall(input: String): String {<br>    val response = client.get(&quot;https://jsonplaceholder.typicode.com/todos/1&quot;)<br>    return input + response.bodyAsText()<br>}<br><br>suspend fun main() {<br>    val response = dummyNetworkCall(&quot;hello&quot;)<br>    println(&quot;dummyNetworkCall Response $response&quot;)<br>}</pre><p>Let’s see how this seemingly synchronous code is converted into asynchronous code by using <strong>CPS</strong>.</p><p>Below is the reduced version of the generated code by the Kotlin compiler</p><pre>private fun dummyNetworkCall(input: String?, completion: Continuation&lt;*&gt;?): Any? {<br><br>    val continuation = completion as? ContinuationImpl ?: object : ContinuationImpl(completion) {<br>        var firstInput: Any? = null<br>        var result: Any? = null<br>        var label: Int = 0<br><br>        public override fun invokeSuspend(result: Any): Any? {<br>            this.result = result<br>            this.label = this.label or Int.Companion.MIN_VALUE // Distinguish fresh or resume call<br>            return dummyNetworkCall(null as String?, this as Continuation&lt;*&gt;)<br>        }<br>    }<br><br>    val var17: StringBuilder<br>    val var10000: Any?<br>    when (continuation.label) {<br>        0 -&gt; {<br><br>            val var26 = HttpStatement(/**/)<br>            continuation.firstInput = input<br>            continuation.label = 1 // Next execution is case 1<br>            var10000 = var26.execute(continuation)<br>            if (var10000 == COROUTINE_SUSPENDED) {<br>                return COROUTINE_SUSPENDED // Nothing to return, wait for callback (i.e., invokeSuspend)<br>            }<br>            break;<br>        }<br><br>        1 -&gt; {<br>            input = continuation.firstInput as String? // restore the state<br>            var10000 = continuation.result // Save result<br>            break; // Break to execute next instruction below when<br>        }<br><br>        2 -&gt; {<br>            var17 = continuation.firstInput as StringBuilder<br>            var10000 = continuation.result<br>            return var17.append(var10000 as String?).toString() // return final result<br>        }<br><br>        else -&gt; throw IllegalStateException(&quot;call to &#39;resume&#39; before &#39;invoke&#39; with coroutine&quot;)<br>    }<br><br>    // After case 1 we get this<br>    val response = var10000 as HttpResponse?<br>    var17 = (StringBuilder()).append(input)<br>    continuation.firstInput = var17<br>    continuation.label = 2 // Next resume point is case 2<br>    var10000 = bodyAsText(response, continuation)<br>    if (var10000 === COROUTINE_SUSPENDED) {<br>        return COROUTINE_SUSPENDED // Nothing to return, wait for callback (i.e., invokeSuspend)<br>    } else {<br>        return var17.append(var10000 as String?).toString()<br>    }<br>}</pre><p>Notice that dummyNetworkCall now takes a continuation object to deliver the result. and not just that, the method now has a when block which was never present in our code.</p><p>The when block introduces different states in the code; wherever we had a suspension point (call to suspend a function), it is converted into a <strong>state</strong> inside the when block. Each <strong>state</strong> dictates what the next block of code should be executed as part of its code, which essentially forms a state machine.</p><p>Each when case represents a distinct state in the execution:</p><ul><li><strong>State 0</strong> represents initial entry: initiates the <strong>network call </strong>and returns <strong>COROUTINE_SUSPENDED</strong> if the result is not yet available, freeing the thread</li><li><strong>State 1 </strong>resumes after the <strong>network call</strong> completes: restores saved state and initiates <strong>bodyAsText() </strong>which again is a suspend function that will return <strong>COROUTINE_SUSPENDED</strong> since the result is not yet available</li><li><strong>State 2</strong> resumes after <strong>bodyAsText() </strong>completes and returns the final result</li></ul><p><strong>COROUTINE_SUSPENDED</strong> is a special value that signals to the coroutine runtime that the result is not yet available. The thread is freed at this point, and <strong>invokeSuspend</strong> will be called later by the runtime to resume execution from the next state.</p><p>Because of this state machine, a coroutine can suspend from one thread and can resume execution from a different thread.</p><p>Refer the video for the execution flow of the state machine</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fq4SGgzhRETs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2Fq4SGgzhRETs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fq4SGgzhRETs%2Fhq2.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f45ba0dbdfa7a0787d8c78c9fbda16ca/href">https://medium.com/media/f45ba0dbdfa7a0787d8c78c9fbda16ca/href</a></iframe><h4>Annexure</h4><ul><li><a href="https://github.com/sridhar-sp/android-playground/tree/main/coroutine-play/app/src/main/java/com/droidstarter/blog">android-playground/coroutine-play/app/src/main/java/com/droidstarter/blog at main · sridhar-sp/android-playground</a></li><li><a href="https://github.com/sponsors/sridhar-sp">Sponsor @sridhar-sp on GitHub Sponsors</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b70506794a6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Cancel a Coroutine Properly]]></title>
            <link>https://medium.com/@sridhar-sp/how-to-cancel-a-coroutine-properly-e91d8f581703?source=rss-8b095914072e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e91d8f581703</guid>
            <category><![CDATA[coroutines-best-practices]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[cooperative-cancellation]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[sridhar subramaniam]]></dc:creator>
            <pubDate>Sun, 28 Jun 2026 16:16:26 GMT</pubDate>
            <atom:updated>2026-06-28T16:16:26.789Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding why cancellation in Kotlin coroutines is a polite request and how to write suspend functions that actually honour it.</p><h3>How to Cancel a Coroutine</h3><p>If we want to cancel a single coroutine, we call cancel on the job object, or we can call cancel on the coroutine scope to cancel all child coroutines launched using it.</p><h4>The Common Misconception: “I Called cancel(), So It’s Cancelled, Right?”</h4><p>No, a coroutine will not be cancelled just because we called the cancel method. it&#39;s the developer&#39;s responsibility to cancel it safely, because we shouldn&#39;t cancel a running operation abruptly, as it can lead to malfunction of the system, data inconsistencies, etc.</p><p>Assume we have an operation which moves one video file from one hard drive to another. What happens if we call cancel and the job is cancelled immediately? The copy would not have completed, and we may end up with corrupted data. This is a fairly low-stakes use case.</p><p>Consider a coroutine that’s placing a food order. It charges the customer’s, then confirms the order with the restaurant. If cancel() stopped execution immediately after the charge but before the order confirmation, the customer&#39;s money is gone, but no order was ever placed. No crash, no error, just a hungry and confused customer.</p><p>In fact, Java made this exact mistake with Thread.stop, introduced in Java 1.0. The method was deprecated as early as JDK 1.1, and its usage has been strongly discouraged for 25+ years. It took almost 30 years for it to be finally removed in JDK 26.</p><p>Oracle’s own migration guidance settled on cooperative cancellation. Like coroutines, the only correct way to stop a thread is to signal it by changing the state of a shared volatile variable, where the thread polls that flag in its run loop and exits cleanly when it&#39;s set.</p><h4>What’s Cooperative Cancellation?</h4><p>A coroutine, as the name implies, is a cooperative routine, which uses cooperative scheduling for its operation, so it’s no wonder it uses cooperative cancellation as well.</p><p>Like we discussed earlier, we don’t stop anything abruptly; instead, we send a signal to gracefully cancel.</p><p>Let’s consider this read file example</p><pre>private suspend fun readFile(filePath: String) = withContext(Dispatchers.IO) {<br>    val resultBuilder = StringBuilder()<br>    val buffer = ByteArray(10 * 1024 * 1024)<br><br>    FileInputStream(filePath).use { stream -&gt;<br>        var bytesRead: Int<br>        while (stream.read(buffer).also { bytesRead = it } != -1) {<br>            resultBuilder.append(String(buffer, 0, bytesRead))<br>            println(&quot;Reading file...&quot;)<br>        }<br>    }<br><br>    println(&quot;File read completed&quot;)<br><br>    resultBuilder.toString()<br>}</pre><p>Above, the suspend function uses Dispatchers.IO to read a file and returns the content as a string. During execution it prints Reading file... to illustrate that the program is still running, and once the file read is complete we get File read completed message printed on the console.</p><p>Consider we have below code to cancel the job in middle (i.e., 1500 ms after program start in this example)</p><pre>private fun nonCooperativeCancellingDemo() {<br>    val filePath = &quot;large_test_file.bin&quot; // 1GB File<br><br>    var readJob: Job? = null<br><br>    val ioScope = CoroutineScope(Dispatchers.IO)<br><br>    runBlocking {<br><br>        readJob = ioScope.launch {<br>            val fileContent = readFile(filePath)<br>            // Below print line will never get printed if we cancel the job before readFile completes, since launch<br>            // uses StandaloneCoroutine<br>            println(&quot;File read success, file size ${fileContent.length}&quot;)<br>        }<br><br>        ioScope.launch {<br>            delay(1500.milliseconds)<br>            println(&quot;Calling cancel on read job&quot;)<br>            readJob!!.cancel()<br>        }<br><br>        readJob!!.join()<br><br>    }<br><br>    println(&quot;End of program&quot;)<br>}</pre><p>Inside runBlocking we start readFile inside ioScope and cancel the job after 1500 milliseconds in the next launch block.</p><p>If we expect our program to stop running (i.e., stop printing Reading file...) after calling cancel(), we would be wrong. This is a common assumption for developers who are not familiar with cooperative scheduling.</p><p>Instead, the program will continue to execute, and we can even see File read completed printed , confirming the coroutine ran to its completion, completely ignoring the cancel() call.</p><p><strong>So what’s the missing piece?</strong></p><p>A control signal is the missing piece, a flag that indicates whether a coroutine is still eligible to run (i.e., isActive in coroutines).</p><p>Let’s rewrite the code to adhere to cooperative cancellation and gracefully exit the read operation.</p><pre>private suspend fun readFileSupportCancellation(filePath: String) = withContext(Dispatchers.IO) {<br>    val resultBuilder = StringBuilder()<br>    val buffer = ByteArray(10 * 1024 * 1024)<br><br>    FileInputStream(filePath).use { stream -&gt;<br>        var bytesRead: Int<br>        while (stream.read(buffer).also { bytesRead = it } != -1) {<br>            if (!isActive) {<br>                println(&quot;Job was cancelled, do necessary clean and gracefully exit.&quot;)<br>                throw CancellationException(&quot;Exiting gracefully&quot;)<br>            }<br>//            ensureActive() // This also can be used to ensure we are active if not throws CancellationException;<br>            resultBuilder.append(String(buffer, 0, bytesRead))<br>            println(&quot;Reading file...&quot;)<br>        }<br>    }<br><br>    println(&quot;File read completed&quot;)<br><br>    resultBuilder.toString()<br>}</pre><p>At each iteration we check whether the coroutine is still active before continuing the operation. If not, we do the necessary cleanup and exit gracefully by throwing CancellationException.</p><p>CancellationException is special here. When a coroutine throws it, the coroutine machinery treats it as normal cancellation rather than a failure. The job transitions to a Cancelled state silently, without forwarding the exception to the parent as an error. This is why you never see a stack trace when a coroutine is cancelled normally.</p><p><strong>What Does <em>Cancel()</em> Actually Do Under the Hood?</strong></p><p>Calling cancel() transitions the Job through a state machine, from Active to Cancelled. As a result of this transition, isActive returns false, which is the signal our code should be checking at each <strong>check</strong> <strong>point</strong> to decide whether to continue or exit gracefully.</p><h3>Conclusion</h3><p>Calling cancel() is not an order, it&#39;s a polite request. Whether your coroutine actually stops, and how cleanly it does so, depends entirely on how cooperatively it was written. As we saw, a coroutine that never checks isActive or calls ensureActive() will simply ignore the request and run to completion.</p><p>This isn’t a flaw in Kotlin coroutines, it’s a deliberate design decision. The next time you write a suspend function, ask yourself: have I given this coroutine enough checkpoints to hear the cancellation signal? And if it does get cancelled mid-way, have I handled the cleanup?</p><p>Cooperative cancellation puts the responsibility on the developer and that’s exactly where it belongs.</p><h4>Important Links</h4><ul><li><a href="https://kotlinlang.org/docs/cancellation-and-timeouts.html#timeout">Cancellation and timeouts | Kotlin</a></li><li><a href="https://docs.oracle.com/javase/8/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html">Java Thread Primitive Deprecation</a></li><li><a href="https://github.com/sponsors/sridhar-sp?source=post_page-----46faa1f692ee---------------------------------------">Sponsor @sridhar-sp on GitHub Sponsors</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e91d8f581703" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Single Core to Coroutines]]></title>
            <link>https://medium.com/@sridhar-sp/from-single-core-to-coroutines-46faa1f692ee?source=rss-8b095914072e------2</link>
            <guid isPermaLink="false">https://medium.com/p/46faa1f692ee</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[thread-pool]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[multithreading]]></category>
            <dc:creator><![CDATA[sridhar subramaniam]]></dc:creator>
            <pubDate>Mon, 20 Apr 2026 15:32:52 GMT</pubDate>
            <atom:updated>2026-07-04T16:46:14.654Z</atom:updated>
            <content:encoded><![CDATA[<p>Exploring Threads, Processes, and the Rise of Coroutines (Part 4)</p><blockquote>In a <a href="https://medium.com/@sridhar-sp/from-single-core-to-coroutines-dfdcc31f06b6">previous blog</a>, we discussed hardware and software threads, context switching and its overhead, and how ThreadPool helps reduce unnecessary context switches by reusing threads. However, even with a ThreadPool, each thread is still an <strong>OS-managed</strong> entity that consumes memory and incurs context switch overhead when blocked on IO. <strong>This is where coroutines come in, a lighter alternative that can handle concurrency more efficiently.</strong></blockquote><h3><strong>What is a coroutine?</strong></h3><p>A <a href="https://en.wikipedia.org/wiki/Coroutine">coroutine</a> is a concurrency primitive that enables <strong>cooperative multitasking</strong>. Unlike OS threads, <strong>task scheduling</strong> happens <strong>at</strong> the <strong>application layer</strong> (user level) rather than the kernel layer. Coroutines are primarily used for <strong>asynchronous</strong>,<strong> non-blocking programming</strong>, reducing the overhead of thread creation, large per-thread memory stacks, and kernel-level context switching.</p><h4>What is Cooperative Multitasking?</h4><p>In Part 3, we saw how the OS scheduler uses preemptive multitasking. (i.e., forcibly taking the CPU away from threads without their cooperation) Coroutines take the opposite approach called cooperative multitasking, also known as non-preemptive multitasking.</p><p>In cooperative multitasking, processes <strong>voluntarily yield control</strong> periodically, when idle, or when logically blocked, allowing other tasks to run on the same thread. This type of multitasking is called ‘<strong>cooperative</strong>’ because all programs must cooperate for the scheduling scheme to work.</p><h4>What Does It Mean to Yield?</h4><p>At any given point, if a program determines it <strong>no longer needs the CPU</strong>, it can <strong>yield control</strong>. But isn’t that what a return statement does?</p><p>Not quite. A <strong>return</strong> statement <strong>signals</strong> that the <strong>function</strong> has <strong>completed</strong> execution. <strong>Yielding</strong>, however, does not indicate completion, but it simply means the program <strong>doesn’t need the CPU right now</strong>, and the dispatcher can schedule other coroutines on the same thread in the meantime.</p><p>At this point the coroutine is said to be <strong>suspended</strong>. It will be resumed later by the dispatcher when triggered by an IO completion, a timer expiring, or another coroutine yielding. This is the essence of cooperative multitasking: that coroutines voluntarily give up CPU time, allowing other tasks to make progress, so all get a fair share of execution time.</p><h4>Why Would a Program Voluntarily Give Up the CPU?</h4><p>Most functions are written to take some input, process it, and return a result, requiring the CPU throughout their execution. It doesn’t make sense to pause or yield in the middle of such work.</p><p>This holds true for CPU-intensive tasks, where the program requires full CPU utilisation to complete. But the same is not true for <strong>IO-intensive </strong>tasks by <strong>nature;</strong> they <strong>spend</strong> most of their <strong>time in a blocked/waiting state</strong>, waiting for an external operation such as a network response or a disk read to complete. During this waiting period, the program doesn’t need the CPU at all, and it doesn’t make sense to hold on to a thread that isn’t actively doing any work. (Check out the <a href="https://medium.com/@sridhar-sp/from-single-core-to-coroutines-dfdcc31f06b6">previous blog</a> to read about <strong>IO-intensive tasks.)</strong></p><p>This is the perfect opportunity to <strong>yield</strong>, yield will suspend the <strong>coroutine</strong> and free up the thread to execute other <strong>coroutines</strong>. Once the IO operation completes, the <strong>coroutine</strong> is resumed exactly where it left off.</p><h3>Mythbuster</h3><blockquote>Coroutines are lightweight, cooperative concurrency primitives that allow functions to suspend execution and resume later <strong>without blocking threads</strong></blockquote><p>Above is the first Google search result, and in most places we would see the above definition for &#39;<strong>coroutine</strong>&#39;. I would like to slightly differ from it by saying, <strong>“Only if we write non-blocking code will the thread not get blocked; otherwise, it will get blocked.”</strong></p><p>If a <strong>blocking</strong> call is made inside a <strong>coroutine</strong>, such as Thread.sleep() or a blocking database or network call, the underlying <strong>thread will still get</strong> <strong>blocked</strong>, regardless of the coroutine wrapper around it.</p><blockquote>Coroutines give you the ability to write non-blocking code elegantly, but they don’t enforce it automatically.</blockquote><p>Let&#39;s understand this using the below example.</p><h3>Let’s do I/O</h3><h4><strong>Blocking I/O</strong></h4><p>Let’s create a simple program to read a huge file in a loop 5 times. Each loop will launch a coroutine using <em>Dispatchers.IO</em>. One might assume the code spawns five threads, and no thread gets blocked, and each thread is free to execute a different coroutine.</p><pre>fun blockingRead(filePath: String): Long {<br>    var totalBytes = 0L<br>    val buffer = ByteArray(200 * 1024 * 1024) // 128KB buffer<br><br>    FileInputStream(filePath).use { stream -&gt;<br>        var bytesRead: Int<br>        while (stream.read(buffer).also { bytesRead = it } != -1) {<br>            totalBytes += bytesRead<br>        }<br>    }<br>    return totalBytes<br>}</pre><pre>fun main() {<br>    val filePath = &quot;large_test_file.bin&quot; // 1GB File<br>    val taskCount = 5<br><br>    runBlocking {<br>        val jobs = List(taskCount) { index -&gt;<br>            launch(Dispatchers.IO) {<br>                println(&quot;[${Thread.currentThread().name}] Blocking read started for index $index&quot;)<br>                repeat(50) {<br>                    blockingRead(filePath)<br>                }<br>                println(&quot;[${Thread.currentThread().name}] Blocking read done for index $index&quot;)<br>            }<br>        }<br><br>        jobs.joinAll()<br>    }<br>}</pre><h4>Result</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ilMamrONT7-_SZ-E9BguVQ.png" /><figcaption>Each thread is blocked till the read is completed.</figcaption></figure><p>As shown in the results above, each thread is tied to one coroutine from start to finish. worker-1 started reading the first file and remained blocked until the entire read completed. The same pattern holds for every other worker, none of them were free to pick up other work during the blocking read.</p><blockquote>Coroutines do <strong>NOT</strong> make blocking IO non-blocking.</blockquote><p>A coroutine does not magically suspend execution and free the thread unless a valid suspension point is explicitly introduced in the code.</p><p>One thing worth highlighting is that the blockingRead function did not have a suspend modifier. But simply adding suspend alone would not have helped either, in fact, the Kotlin compiler would show a warning: redundant suspend modifier.</p><p>A function is only truly suspending if it contains at least one suspension point<strong> (</strong>i.e.,<strong> <em>a call to another suspend function or a coroutine primitive such as delay()</em></strong>). The suspend modifier alone, without any suspension points inside the function body, means nothing to the coroutine runtime.</p><p>This leads us naturally to the next question — what exactly is a suspend function, and how do we write one correctly? <strong>We’ll cover that in the next blog.</strong></p><p>Now Let’s use a non-blocking IO function and see the results</p><h4>Non-Blocking I/O</h4><p>The FileInputStream uses read() function under the hood that is a blocking call, hence the thread which made the read also gets <strong>blocked/waiting </strong>depends on the implementation. (either case the thread is not free to execute any other code.)</p><p>Whenever we encounter an <strong>IO operation</strong> such as a read or write, our thread has nothing to do until the data arrives from the endpoint, be it a network call or a disk read. During this time, the thread sits in a <strong>blocked/waiting</strong> state and is only set back to runnable once the data is received.</p><p>One way to avoid this is by using a callback mechanism. Instead of waiting for the result, we provide the read function with a buffer to fill and a <strong>callback to notify </strong>us once the read completes or fails. The thread only executes the instruction to initiate the read, which is asynchronous, meaning the result will be delivered later. Once the read call is made, the thread has no more instructions to execute. If it was a<strong> standalone thread,</strong> it will move to a <strong>stopped</strong> state; if it came from a <strong>ThreadPool</strong>, it will be <strong>parked</strong> and made available for other tasks.</p><p>Once the IO operation completes, the callback is executed by a new thread. From within the callback, we can then submit the remaining work back to our thread pool to continue processing.</p><p>This is achieved using Java NIO, which provides asynchronous IO primitives such as AsynchronousFileChannel and CompletionHandler.</p><p>Let’s look at the below function, nonBlockingFileRead which uses AsynchronousFileChannel the read function, which is <strong>a non-blocking</strong> call. (i.e., the thread will not wait for the result). The method takes a buffer object and returns a <strong>Future</strong> object immediately once it is executed; the result from the buffer can be read once we get the completion callback, which will be called from some<strong> other internal thread</strong> managed by the Java <strong>NIO framework.</strong></p><p>Let’s look at the nonBlockingFileRead function below, which uses AsynchronousFileChannel (part of Java NIO.2). The read call is <strong>non-blocking</strong>, meaning the thread will not wait for the result. Instead, we pass a CompletionHandler callback that gets invoked by an <strong>internal thread</strong> managed by the Java NIO.2 framework once the read finishes or fails.</p><pre>suspend fun nonBlockingFileRead(filePath: String): Long {<br>    val path = java.nio.file.Paths.get(filePath)<br>    val channel = AsynchronousFileChannel.open(path, StandardOpenOption.READ)<br><br>    val fileSize = channel.size()<br>    val buffer = ByteBuffer.allocate(fileSize.toInt())<br><br>    // read entire file — suspends coroutine, does NOT block thread<br>    val totalBytes = suspendCoroutine { continuation -&gt;<br>        channel.read( // Async function; returns a Future <br>            buffer, 0L, null,<br>            object : CompletionHandler&lt;Int, Nothing?&gt; {<br><br>                override fun completed(bytesRead: Int, attachment: Nothing?) {<br>                    // Invoked by the JVM&#39;s internal IO thread once the read operation finishes.<br>                    // We resume the suspended coroutine here, passing the result (bytes read).<br>                    // The coroutine will be dispatched back to the thread determined by the<br>                    // scope&#39;s dispatcher (e.g., Dispatchers.IO), not the internal IO thread.<br>                    continuation.resume(bytesRead.toLong())<br>                }<br><br>                override fun failed(exc: Throwable, attachment: Nothing?) {<br>                    continuation.resumeWithException(exc)<br>                }<br>            }<br>        )<br>    }<br><br>    channel.close()<br><br>    return totalBytes<br>}</pre><p>The main function is similar to the blocking IO example, with one small addition, we now launch another <strong>coroutine</strong> alongside each read that simply prints a message after a short delay. This is to demonstrate that while the non-blocking read is in progress, the dispatcher’s thread pool is free to pick up and execute other coroutines. Unlike the blocking IO example, where each thread was tied up for the entire duration of the read, here the threads are not blocked, they are available to execute other work. (It’s not guaranteed that the thread started read operation will get a chance to execute the other <strong>coroutine</strong>, but through multiple runs we can observe such a scenario</p><pre>fun main() {<br>    val filePath = &quot;large_test_file.bin&quot; // 1GB File<br>    val taskCount = 5<br><br>    runBlocking {<br>        val jobs = List(taskCount) { index -&gt;<br>            launch(Dispatchers.IO) {<br>                println(&quot;[${Thread.currentThread().name}] Non-Blocking read started for index $index&quot;)<br>                nonBlockingFileRead(filePath)<br>                println(&quot;[${Thread.currentThread().name}] Non-Blocking read done for index $index&quot;)<br>            }<br>            launch(Dispatchers.IO) {<br>                delay(500)<br>                println(&quot;Other task running on [${Thread.currentThread().name}]&quot;)<br>            }<br>        }<br><br>        jobs.joinAll()<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rtQiR4fCGLOmfn4ZE8uz_w.png" /></figure><p>From the results, we can see that the read operation for index 4 was started by worker-3. Yet a few lines later, the same worker-3 is running another task, while the read is still in progress. <strong>This is a clear indication that the thread was not blocked or waiting during the read operation.</strong></p><p>Furthermore, looking further down in the logs, the read for index 4 was completed and resumed on worker-4 not worker-3 that initiated it. Similarly, index 0 was started by worker-1 but completed on worker-3. This confirms that <strong>coroutines</strong> are not tied to a specific thread — after a suspension point, the <strong>coroutine</strong> can be resumed on any available thread in the dispatcher’s pool.</p><h3>Where is yield?</h3><p>You may have noticed that we have not explicitly called yield anywhere in this example. One could also argue that the same result for <strong>non-blocking</strong> <strong>IO</strong> can be achieved using a ThreadPool, where the thread that initiates the read is freed up to execute other tasks. That is true, and the results would be similar.</p><p>However, there is a key difference, to achieve this with a ThreadPool, we would have to restructure our code around callbacks. And as the number of chained async operations grows, this quickly leads to deeply nested, hard-to-read code commonly known as <strong>callback hell</strong>.</p><p>Also, in our Java NIO example, the yielding happened implicitly, the read operation was handed off to an internal thread managed by the NIO framework, naturally freeing our thread without us explicitly calling yield.</p><p>In the next blog, we will go deeper into:</p><ul><li>What <strong>yield</strong> is and when to call it explicitly</li><li>What <strong>callback hell</strong> is and why it motivated the coroutine model</li><li>What <strong>Continuation Passing Style (CPS)</strong> is and how Kotlin uses it under the hood to implement suspension</li><li>What <strong>structured concurrency</strong> is and how Kotlin enforces it through scopes and job hierarchies</li></ul><p>By the end of the next blog, the full picture of how coroutines work from suspension to resumption will be complete.</p><p>Next Blog</p><p><a href="https://medium.com/@sridhar-sp/from-single-core-to-coroutines-b70506794a6b">From Single Core to Coroutines</a></p><h3>Annexure</h3><p>Why does a regular read function block? Let&#39;s trace the read function call stack. We can see the call to <strong>folio_wait_bit_common</strong>, which sets the thread state to waiting for a particular file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pDfbhPKx1384cImrNGfeig.png" /><figcaption>Call stack of a read call</figcaption></figure><p><a href="https://github.com/sponsors/sridhar-sp">Sponsor @sridhar-sp on GitHub Sponsors</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46faa1f692ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Single Core to Coroutines]]></title>
            <link>https://medium.com/@sridhar-sp/from-single-core-to-coroutines-dfdcc31f06b6?source=rss-8b095914072e------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfdcc31f06b6</guid>
            <category><![CDATA[executorservice]]></category>
            <category><![CDATA[thread-pool]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[sridhar subramaniam]]></dc:creator>
            <pubDate>Mon, 20 Apr 2026 15:09:30 GMT</pubDate>
            <atom:updated>2026-05-27T12:03:34.443Z</atom:updated>
            <content:encoded><![CDATA[<p>Exploring Threads, Processes, and the Rise of Coroutines (Part 3)</p><blockquote>In a <a href="https://medium.com/@sridhar-sp/from-single-core-to-coroutines-bad184b17c8d">previous blog</a>, we discussed parallel vs concurrent execution, context switching and the cost of it. <strong>Now let’s discuss how to minimise it.</strong></blockquote><blockquote>Recap: Creating too many threads individually consumes significant system resources and increases context switching overhead. This is where the concept of a ThreadPool comes to the rescue.</blockquote><h3><strong>What is a ThreadPool?</strong></h3><p>Instead of creating random individual threads on demand for concurrent operations, we can use the ThreadPool, which manages a pool of reusable threads to execute the task concurrently.</p><p>In Java we have ExecutorService, which provides various thread pool implementations. Each serves unique purposes.</p><ul><li><strong>CachedThreadPool</strong> -&gt; Unbounded Thread (creates new threads as needed and reuses idle ones)</li><li><strong>FixedThreadPool</strong> -&gt; Bounded Thread, Unbounded Tasks</li><li><strong>SingleThreadExecutor</strong> -&gt; Single Thread, Unbounded Tasks</li><li><strong>ScheduledThreadPool</strong> -&gt; Manages delayed and periodic task execution.</li></ul><blockquote>Task is a runnable action (i.e code to be executed on a thread)</blockquote><h4><strong>Identifying the Suitable ThreadPool</strong></h4><p>Selecting the right thread pool depends on the application use case.</p><p>Assume we have an <strong>8-core system</strong> without hyperthreading, giving us <strong>8 hardware threads</strong>. In this configuration, only 8 threads can execute truly in parallel.</p><blockquote>Note: So far in our blog we have represented a core as a hardware thread for simplicity, but industry calls a core a physical independent execution unit, and hardware threads are logical separations within a core that allow it to switch between multiple tasks, hiding latency and improving utilization of the core’s execution units.</blockquote><blockquote>A hardware thread is also called a logical core/processor.</blockquote><p><strong>ThreadPool for CPU-Intensive Operation</strong></p><p>Assume we have a CPU-intensive operation like calculating prime numbers or performing cryptographic calculations, which require full CPU utilisation.F We can use a fixed thread pool with the size of the number of CPU cores in the system. (i.e., 8 as per our example)</p><p>At any given point in time, only 8 threads can be in the executing state; the rest will be in the waiting or blocking state. Creating a thread pool larger than the total number of cores will only increase the total number of threads in the system, and the CPU has to rapidly switch between them, which incurs a context switch time. Also, the increased number of threads will only increase the chance of a thread being put in a parked state since the CPU can execute 8 threads in parallel (as per our configuration mentioned above).</p><p>For CPU-intensive tasks, parked threads add no value; they only delay the overall computation. So for CPU-intensive workloads, matching the thread pool size to the number of cores is the optimal choice.</p><p><strong>ThreadPool for I/O-Intensive Operation</strong></p><p>For IO-intensive operations, such as writing system logs, scanning the file system, or syncing server time, a higher thread count is appropriate. Most of the time, IO threads spend the majority of their time in a blocked/waiting state waiting for a response. For example, a thread connecting to a server must wait until the server responds. During this time, the scheduler parks the thread, marking it as ineligible for execution until the IO completes or an interrupt occurs. Since blocked threads don’t consume CPU cycles, having more threads than cores is acceptable and doesn’t significantly increase context switch overhead.</p><h3>Does ThreadPool eliminate context switching?</h3><p>Using a ThreadPool with an appropriate size helps <strong>reduce unnecessary context switching overhead</strong>, as it limits the total number of active threads competing for CPU time. It doesn’t eliminate context switching altogether. Context switches will still happen due to:</p><ul><li>I/O blocking</li><li>Interrupts</li><li>OS scheduler preemption</li><li>Other processes/threads running on the system outside your thread pool</li></ul><h4>What is OS Scheduler Preemption?</h4><p>The OS scheduler uses <strong>preemptive multitasking.</strong> It can forcibly take the CPU away from a running thread at any time, <strong>without the thread’s cooperation,</strong> to give another thread a chance to execute. This is fundamentally different from cooperative multitasking, where tasks voluntarily yield control.</p><p>We will explore cooperative multitasking and how coroutines use it in the upcoming blog.</p><h3>Let’s See Some Code</h3><h4>CPU-Intensive Work</h4><p>As discussed earlier, CPU-intensive tasks require full CPU utilisation throughout their execution and have no natural point at which they would block. Consider the following CPU-intensive task (simplified using sqrt).</p><pre>private fun cpuIntensiveTask(): Long {<br>    var result = 0L<br>    for (i in 0 until 10_000_000) {<br>        // CPU-intensive work: Like calculating hash for a huge file<br>        result += sqrt(i.toDouble()).toLong()  // real computation<br>    }<br>    return result<br>}</pre><pre>fun main() {<br>    val availableProcessors = Runtime.getRuntime().availableProcessors()<br>    println(&quot;Available Processors: $availableProcessors&quot;)<br><br>    // JIT warm-up: runs the task a few times so the JVM can compile<br>    // and optimize the hot code path before the actual benchmark begins<br>    repeat(3) { cpuIntensiveTask() }<br>    println(&quot;=&quot;.repeat(60))<br><br>    val baselineTaskTimeTakenList = mutableListOf&lt;Long&gt;()<br>    // Baseline test<br>    repeat(3) {<br>        val timeTaken = measureTimeMillis { cpuIntensiveTask() }<br>        baselineTaskTimeTakenList.add(timeTaken)<br>    }<br>    println(&quot;=&quot;.repeat(60))<br><br>    val futureList = mutableListOf&lt;Future&lt;*&gt;&gt;()<br>    val taskTimeTakenList = mutableListOf&lt;Long&gt;()<br>    val executor = Executors.newFixedThreadPool(availableProcessors)<br>   // Actual test using default dispatcher; Modify limit to check task time<br>    for (i in 0 until availableProcessors) {<br>        val future = executor.submit {<br>            val timeTaken = measureTimeMillis { cpuIntensiveTask() }<br>            taskTimeTakenList.add(timeTaken)<br>        }<br>        futureList.add(future)<br>    }<br><br>    futureList.forEach { it.get() }<br><br>    drawBarGraph(&quot;Baseline&quot;, baselineTaskTimeTakenList)<br>    drawBarGraph(&quot;Test&quot;, taskTimeTakenList)<br>}</pre><p>I have a 20-core machine. At the time of recording this baseline, I had multiple Chrome windows and a couple of IDEs open, so the results are not from a controlled environment and may vary across runs depending on system load and available resources.</p><p>If we run the for loop 20 times (i.e., equal to the available processor count), below are the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jMnRfYgBDZMmEl5xxKmjMA.png" /><figcaption>Running 20 CPU-intensive tasks on a 20-core processor</figcaption></figure><p>The baseline shows the function took an average of 32ms to complete. In the actual test, around 8 tasks were completed before 36ms, another 8 tasks around 44ms, and only 2 tasks reaching 50ms</p><p>The function ideally should take around 32ms in this run, but in a few cases it’s reaching 50ms. This is expected since this is not a controlled environment; other processes from other applications may have caused occasional context switches.</p><p>If we run the for loop 40 times (i.e., twice the available processor count), below are the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m6dowGBfsyQGD-EUzW8FnQ.png" /><figcaption>Running 40 CPU-intensive tasks on a 20-core processor</figcaption></figure><p>The baseline shows the function took an average of 31msto complete. In the actual test, 2 tasks were completed in 30ms, around 20 tasks were completed before 40ms, another 14 tasks between 40–50ms, and 2 tasks reaching 80ms.</p><p>The function ideally should take around 31ms in this run, but 2 tasks took as long as 80ms. This is because we submitted 40 tasks to a 20-core system, only 20 threads can execute truly in parallel at any given time. The remaining 20 threads compete for CPU time, <strong>forcing</strong> the <strong>scheduler</strong> to <strong>context switch between them</strong>. This additional context switch overhead directly increases the time taken to complete the computation, <strong>which is exactly why oversizing a thread pool for CPU-intensive tasks is counterproductive.</strong></p><blockquote>For a deeper look at context switching overhead, refer to our <a href="https://medium.com/@sridhar-sp/from-single-core-to-coroutines-bad184b17c8d">previous blog</a> where we benchmarked context switch time using lmbench.</blockquote><h4>IO-Intensive Work</h4><p>Let’s now modify the code to perform IO-intensive operation and increase the thread pool count to 128 (much higher than 20 processor count)</p><pre>private fun ioIntensiveTask(): Int {<br><br>    var totalLines = 0<br>    repeat(50) {<br>        totalLines += java.io.File(&quot;SixKiloByteFile.txt&quot;).readLines().size<br>    }<br><br>    return totalLines<br>}</pre><blockquote>Note: main function code stays similar; only the thread pool size and for loop limit are increased.</blockquote><pre>fun main() {<br>    // ... Refer CPU-intensive section for full code<br>    val executor = Executors.newFixedThreadPool(128)<br>   // Actual test using default dispatcher; Modify limit to check task time<br>    for (i in 0 until availableProcessors) { // 20, 60, 120 etc <br>        val future = executor.submit {<br>            val timeTaken = measureTimeMillis { ioIntensiveTask() }<br>            taskTimeTakenList.add(timeTaken)<br>        }<br>        futureList.add(future)<br>    }<br>    // ... Refer CPU-intensive section for full code<br>}</pre><p>If we run 20 tasks on a 20-thread machine with a thread pool size of 128, our baseline average is 3.7ms per task, and the actual test average comes around 13ms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FFXWRT5LqLcP_1wgXDVdsA.png" /><figcaption>Running 20 IO-intensive tasks on a 20-core processor with a thread pool size of 128</figcaption></figure><p>If we increase the number of tasks to 60 and then 120, the baseline average are 10.6ms and 7.5ms respectively, and we see interesting results with the actual test average time that drops to around 10.6ms for 60 tasks (roughly 3ms less than the 20-task run) and further down to around 7.5ms for 120 tasks, which is nearly 50% less than the 20-task average.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QAb6kpzAvDG3murOfFd70A.png" /><figcaption>Test results of running 60 and 120 IO-intensive task on a 20-core processor with a thread pool size of 128</figcaption></figure><p>This might seem counterintuitive at first. How are more tasks completed faster?</p><p>But this is exactly where IO-intensive tasks behave differently from CPU-intensive ones. Since <strong>most IO threads spend the majority of their time in a blocked/waiting state</strong> waiting for an external operation to complete, the CPU is largely free. The thread pool can keep scheduling other threads during this waiting period, effectively keeping the CPU busy with useful work rather than sitting idle. This is why we need a larger number of threads for I/O operations compared to CPU-intensive operations.</p><h4>Next Blog</h4><ul><li><a href="https://medium.com/@sridhar-sp/from-single-core-to-coroutines-46faa1f692ee">From Single Core to Coroutines</a></li><li><a href="https://github.com/sponsors/sridhar-sp">Sponsor @sridhar-sp on GitHub Sponsors</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfdcc31f06b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Single Core to Coroutines]]></title>
            <link>https://medium.com/@sridhar-sp/from-single-core-to-coroutines-bad184b17c8d?source=rss-8b095914072e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bad184b17c8d</guid>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <dc:creator><![CDATA[sridhar subramaniam]]></dc:creator>
            <pubDate>Sun, 19 Apr 2026 14:58:41 GMT</pubDate>
            <atom:updated>2026-05-27T12:03:13.356Z</atom:updated>
            <content:encoded><![CDATA[<p>Exploring Threads, Processes, and the Rise of Coroutines (Part 2)</p><blockquote>In a <a href="https://medium.com/@sridhar-sp/from-single-core-to-coroutines-213992f8b2d1">previous blog</a>, we discussed what a thread and a process are and how many threads we can truly have in the system. <strong>Now let’s discuss concurrent vs parallel.</strong></blockquote><h3>What is parallel execution?</h3><p>The ability to run multiple tasks simultaneously in the CPU. As we discussed earlier, a single CPU die can contain multiple cores, enabling true parallel execution</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h1XuinpE_JN20fHVLurdFw.png" /><figcaption>Parallel Execution</figcaption></figure><h3>What is concurrent execution?</h3><p>The ability to manage multiple things at once. “Manage” is the keyword here, because a concurrent execution system manages tasks in such a way that each gets executed for a fair amount of time, giving us the illusion of them all happening at the same time. But in reality, on a single core, tasks are interleaved, each getting a slice of CPU time rather than running truly simultaneously.</p><blockquote>Note: Concurrency is possible with multiple cores as well; concurrency is about <strong>structure/management</strong> of tasks.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ukSqISwyCny-bk4pvkfCQ.png" /><figcaption>Concurrent Execution</figcaption></figure><h3>History of Parallel vs Concurrent</h3><p>The world’s first microprocessor, the <a href="https://en.wikipedia.org/wiki/Intel_4004">Intel 4004</a>, introduced in 1971, was a 4-bit processor. It was capable of executing one instruction at a time and did not have multiple cores or hardware threads like modern processors. Therefore, the Intel 4004 could effectively execute only one thread of instructions at a time.</p><p>Fast forward to 2001: IBM released the <a href="https://en.wikipedia.org/wiki/POWER4">Power4</a>, a multicore microprocessor with two cores on a single die. The following year, Intel introduced Hyper-Threading technology with the launch of the Pentium 4 processor around 2002.</p><p>Between 1971 and 2001, the vast majority of mainstream microprocessors had a single core on a single CPU die, so parallel execution was not widely possible from a single chip.</p><blockquote>During these times and even before, parallel execution was possible by using more than one CPU on the system (Symmetric Multiprocessing), but for our discussion we are considering parallel execution support from a single CPU die.</blockquote><p>Before the advent of multi-threading technology, multiple software tasks could run concurrently on a processor through a technique called time-sharing or multitasking. Below are some of those techniques.</p><ul><li><strong>Time-Slicing</strong></li><li><strong>Task Switching</strong></li><li><strong>Interrupt Handling</strong></li><li><strong>Priority-Based Scheduling</strong></li><li><strong>Preemption</strong> → The OS forcibly takes the CPU away from a running task when its time slice expires or a higher-priority task arrives.</li></ul><p>This way, even though the Pentium 3 processor didn’t have hardware support for multi-threading like Hyper-Threading, it could still handle multiple tasks concurrently through time-sharing and task-switching mechanisms provided by the operating system.</p><h3>How a single-core processor was able to run multiple applications, emulating parallel execution</h3><p>The ability of a single-core processor to run multiple applications at once is an illusion created by using an <strong>effective scheduling algorithm</strong> and rapid <strong>context switching</strong>.</p><p>To the human eye, it looks like the music player and the web browser are running in parallel, but at the hardware level, the CPU is rapidly switching between them at incredible speeds.</p><p>Even the old CPUs, like the <a href="https://en.wikipedia.org/wiki/Pentium_(original)">Pentium 1</a>, used to run over 100 million instructions per second. A Pentium 4 (Single Core) could run ~3,000–9,000 million instructions per second. So the CPU can juggle different application executions, giving the illusion of parallel computing.</p><h3>What is Context Switching?</h3><p>The word <strong>“context”</strong> refers to the <strong>state of a thread </strong>at a given point in time, which the OS <strong>saves</strong> when pausing a thread and <strong>restores</strong> when resuming it.</p><p>The thread executing on a CPU core at any given time must eventually be taken off the CPU to allow other threads to execute. Context switches happen for various reasons. The allotted time expires, the thread blocks on I/O, an interrupt occurs, etc.</p><p>The OS must safely offload the currently executing thread and load the next one. This requires careful saving and restoration of CPU state. The outgoing thread’s register values and memory context must be saved, and the incoming thread’s previously saved state must be restored onto the CPU so it resumes exactly where it left off.</p><p>The <a href="https://github.com/torvalds/linux/blob/master/kernel/sched/core.c">kernel/sched/core.c </a>file defines the method required for context switching (i.e., <a href="https://github.com/torvalds/linux/blob/master/kernel/sched/core.c">context_switch</a>) which swaps memory if required and calls other methods that switch the register state and stack pointer.</p><h4>Not All Context Switches Are Equal</h4><ul><li><strong>Thread Switch:</strong> If two threads belong to the same process, they share the same <strong>mm_struct</strong>. The kernel keeps the current memory map active.</li><li><strong>Process Switch:</strong> If the next task has a different <strong>mm_struct </strong>(i.e., from a different process), the kernel must swap the entire memory environment. This is <strong>expensive</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*34zwgjb8QWv4g8NOEDVieA.png" /><figcaption>Context switch code flow</figcaption></figure><h3>Cost of Context Switching</h3><p>Context switching has a cost, each thread must be taken off the CPU once its allotted time expires or an interrupt arrives.</p><p>Modern average CPUs used in everyday use can come with 8 to 16 CPU cores. Assume the CPU has 8 cores; only 8 threads can execute in parallel at a given point in time, and an average computer can easily have around 150–200 threads running after login. On top of that, user programs can contribute to increasing the active number of threads from different applications. Assume we are running 1000 threads in the system from various applications, but we have only 8 cores, so the other 992 threads will be in a waiting state when 8 threads are actively executed by the CPU core, and the CPU rapidly switches between other threads to keep all applications running without any lag.</p><p>The rapid switching comes with a cost.</p><p>Calculating the exact context switch duration is tricky and varies based on several factors:</p><ul><li>Whether it is a thread switch or a process switch</li><li>Cache state -&gt; whether the incoming thread’s data is already warm in L1/L2/L3 cache, or has been evicted to RAM</li><li>etc.</li></ul><p><strong>Commands in Linux</strong></p><ul><li>sar -w 1 -&gt; Show the number of context switches that happen per second.</li><li>pidstat -w 1 -&gt; To see context switches on a per-process or per-thread basis.</li></ul><h4>Time Taken For Context Switch</h4><p>Let’s look at the actual time spent on context switching using <a href="https://github.com/intel/lmbench">lmbench</a> a tool commonly used for measuring OS-level latency.<br>We use lat_ctx with a <strong>0KB</strong> working set size across 2, 4, and 8 processes:</p><pre>./lat_ctx -s 0 2 4 8<br><br>&quot;size=0k ovr=0.28<br>2 1.40 // 2 process switching, Context switch time = 1.40 µs<br>4 1.95 // 4 process switching, Context switch time = 1.95 µs<br>8 2.88 // 8 process switching, Context switch time = 2.88 µs</pre><p>Notice that as the number of processes increases, context switch time grows as well, from 1.40µs for 2 processes to 2.88µs for 8. More processes mean greater pressure on CPU caches and more state to save and restore.</p><p>Just for comparison, it takes around 6µs on my machine to calculate the last 5-digit prime number (99991) using the <a href="https://www.geeksforgeeks.org/dsa/trial-division-algorithm-for-prime-factorization/">trial division method</a> to give a sense of how significant context switch overhead can be relative to actual computation.</p><p><strong>Note:</strong> Context switching is inevitable in modern systems, but we can reduce its impact by moving from OS-managed threads to application-managed concurrency primitives like coroutines. We will discuss more on this in the upcoming blogs.</p><h4>Next Blog</h4><ul><li><a href="https://medium.com/@sridhar-sp/from-single-core-to-coroutines-dfdcc31f06b6">From Single Core to Coroutines</a></li><li><a href="https://github.com/sponsors/sridhar-sp">Sponsor @sridhar-sp on GitHub Sponsors</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bad184b17c8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Single Core to Coroutines]]></title>
            <link>https://medium.com/@sridhar-sp/from-single-core-to-coroutines-213992f8b2d1?source=rss-8b095914072e------2</link>
            <guid isPermaLink="false">https://medium.com/p/213992f8b2d1</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <dc:creator><![CDATA[sridhar subramaniam]]></dc:creator>
            <pubDate>Sun, 19 Apr 2026 14:54:19 GMT</pubDate>
            <atom:updated>2026-05-27T12:02:49.447Z</atom:updated>
            <content:encoded><![CDATA[<p>Exploring Threads, Processes, and the Rise of Coroutines (Part 1)</p><h3>Agenda</h3><p>This blog aims to explore the power of coroutines. Before doing so, we will first dive deep into threads to understand the problems coroutines are designed to solve. The threading concepts discussed largely apply to Linux systems, with some variations in Windows environments.</p><h3>What is Thread?</h3><p>This definition differs based on context (i.e., software or hardware).</p><h4><strong>Software</strong></h4><blockquote>A thread is an abstraction provided by the operating system to execute a sequence of instructions independently.</blockquote><p><strong>In Linux</strong></p><blockquote>A thread is a sequence of instructions that can run independently inside a process, sharing the same memory address space, file descriptors, and other resources of that process.</blockquote><h4><strong>Types of Thread</strong></h4><ol><li><strong>Application Thread — </strong>Managed by the application runtime <em>(also called a User-Level Thread)</em></li><li><strong>OS Thread / Kernel Thread</strong> — Managed by the operating system kernel</li></ol><h4><strong>Hardware</strong></h4><ol><li><strong>CPU Thread</strong></li></ol><p>In hardware, a <strong>CPU thread</strong> (also called a <strong>hardware thread</strong> or <strong>logical processor</strong>) is an <strong>execution context</strong> inside a CPU core that allows the processor to execute instructions.</p><p><em>A </em><strong><em>CPU thread</em></strong><em> represents a logical execution unit that the operating system can schedule work onto. </em>Unlike software threads, which exist in programs, CPU threads are <strong>physical capabilities built into the processor</strong>.</p><p>A modern CPU contains the following:</p><ul><li><strong>CPU</strong> → the whole processor</li><li><strong>Cores</strong> → physical processing units</li><li><strong>CPU Threads</strong> → logical execution slots inside each core; each CPU thread can run one stream of instructions at a time</li></ul><p><strong>CPU Structure Example</strong></p><p>A <strong>single</strong> <a href="https://www.intel.com/content/www/us/en/products/sku/236783/intel-core-i7-processor-14700k-33m-cache-up-to-5-60-ghz/specifications.html">Intel® Core™ i7 processor 14700K</a> <strong>CPU </strong>has 12 <strong>cores</strong> and 28 <strong>threads.</strong></p><p>Each <strong>core</strong> supports <strong>2 CPU threads</strong> using <a href="https://www.intel.com/content/www/us/en/gaming/resources/hyper-threading.html"><strong>Intel Hyper-Threading</strong> </a>(i.e., The CPU exposes two execution contexts per physical core.)</p><blockquote>Note: AMD calls this technique as <a href="https://www.amd.com/en/blogs/2025/simultaneous-multithreading-driving-performance-a.html">Simultaneous Multithreading (SMT)</a></blockquote><h3>Why do we need Thread? Can we do anything without Thread?</h3><p>Threads are an execution abstraction used by operating systems and software. A <strong>thread</strong> represents the <strong>execution path</strong> of instructions.</p><p>The CPU executes instructions through an <strong>execution context,</strong> and in operating systems that execution context is called a <strong>thread</strong>.</p><p>Without a thread:</p><ul><li>No instructions are scheduled</li><li>No code runs</li><li>The process just exists as inactive memory</li></ul><p>So execution is impossible.</p><h3>What is a Process?</h3><p>The process is a <strong>task</strong> that is a schedulable unit of execution that can be scheduled to run on a given processor. A process not only references the program code (aka <strong>text section</strong>) but also includes a set of resources such as open files (stdin, stdout, stderr), signals, memory address space, data section for global variables, etc.</p><p><a href="https://github.com/torvalds/linux/blob/master/include/linux/sched.h">sched.h</a> is a <strong>Linux kernel header file</strong> that defines the <strong>core data structures and APIs used for process and thread scheduling</strong>.</p><p>In Linux, <strong>struct</strong> <strong>task_struct</strong> is the data structure that holds the information about the process/thread. It’s called a task, not a process or thread, because the<strong> kernel represents both using the same structure</strong>. The kernel makes no structural distinction between them at the data structure level.</p><p>What makes something a <strong>thread</strong> vs a <strong>process</strong> is simply what it shares with other <strong>task_struct</strong> instances:</p><ul><li>pid_t <strong>pid</strong>; // unique for every task_struct (every thread has its own)</li><li>pid_t <strong>tgid</strong>; // Thread Group ID — same for all threads of the same process</li></ul><blockquote><em>In Linux, a </em><strong><em>task = Process or Thread</em></strong></blockquote><h4>What task_struct Contains</h4><p><strong>task_struct</strong> — The big picture of a task (process/thread)</p><p>It holds everything the kernel needs to <strong>manage and schedule</strong> a task:</p><ul><li><strong>Identity</strong> →pid, tgid, process name</li><li><strong>State</strong> → running, sleeping, stopped, zombie, etc.</li><li><strong>Scheduling info </strong>→ priority, policy (CFS, RT, etc.), time slices</li><li><strong>Memory</strong> → pointer to mm_struct (address space, heap, stack mappings)</li><li><strong>File system </strong>→ open file descriptors, current working directory</li><li><strong>Signals</strong> → pending signals, signal handlers</li><li><strong>Parent/child relationships</strong> → pointers to parent, children, siblings</li><li><strong>Credentials</strong> → user ID, group ID (for permissions)</li><li><strong>Thread group info</strong> → tgid pointer to thread group leader</li><li><strong>Pointer to </strong><strong>thread_struct</strong> → via the thread field (CPU-specific state of this task)</li></ul><p><strong>thread_struct</strong> → The low-level CPU context of a task</p><p>It holds everything needed to <strong>save and restore CPU state</strong> during a context switch:</p><ul><li><strong>Instruction pointer</strong> → where execution resumes after a context switch</li><li><strong>Stack pointer</strong> → kernel stack pointer</li><li><strong>etc.</strong></li></ul><p><a href="https://github.com/torvalds/linux/blob/master/arch/arm64/include/asm/processor.h"><strong>thread_struct</strong></a> is <strong>embedded inside</strong> <a href="https://github.com/torvalds/linux/blob/master/include/linux/sched.h"><strong>task_struct</strong></a> via the thread field, so they travel together. The kernel uses task_struct to decide who runs next and thread_structto <em>restore where they left off</em>.</p><h4>How Threads are Linked</h4><p>In <strong>task_struct</strong> there is only one <strong>thread_struct</strong> field; now the question may arise of how other threads created for the same process are linked or stored.</p><p>In Linux, each <strong>task_struct</strong> represents exactly one thread. There is no concept of a container holding multiple threads within a single <strong>task_struct</strong>.</p><p>Linux groups them using a shared <strong>tgid</strong> and <strong>shared resources</strong> (memory, file descriptors, and signals) to make them appear as a single process to userspace.</p><ul><li><strong>tgid</strong> —&gt; Thread Group ID. This is what userspace calls PID. The same for all threads belonging to the same process.</li><li><strong>pid </strong>—&gt; Process ID, a unique ID assigned to this specific thread by the kernel.</li></ul><blockquote>So saying a thread is a lightweight process or a process containing a thread may not be accurate in Linux.</blockquote><blockquote>Linux takes an interesting approach to thread support: It does not differentiate between threads and normal processes. To the kernel, all processes are the same — some just happen to share resources. by “Robert Love”</blockquote><h3>How Many Threads Can We Truly Have?</h3><p>The hardware thread is fixed in size as per the CPU design. The software thread, however, depends on the memory we have in the system.</p><p>Every thread needs its own <strong>stack</strong>. The default stack size is typically <strong>8 KB</strong> (32-bit) or <strong>16 KB</strong> (64-bit) per kernel thread. The application thread, like the Java thread, can take ~1MB of initial space. (can be configured with -Xss JVM Flag)</p><p><a href="https://android.googlesource.com/kernel/common/+/35556bed836f/kernel/fork.c"><strong>Max Threads Calculation</strong></a></p><blockquote><strong><em>Max Threads</em></strong><em> = </em><strong><em>TOTAL_RAM_MEMORY</em></strong><em> / (</em><strong><em>THREAD_SIZE * 8</em></strong><em>)</em></blockquote><p><strong>The “Magic 8” Calculation</strong></p><p>By default, the Linux kernel (specifically in <a href="https://android.googlesource.com/kernel/common/+/35556bed836f/kernel/fork.c">fork.c</a>) limits the total number of threads so that their combined <strong>kernel stacks</strong> do not consume more than <strong>12.5% (1/8th)</strong> of your total available RAM. This leaves the remaining 87.5% for the actual data your threads are supposed to be processing.</p><p>On a 64-bit system with</p><ul><li><strong>Total RAM:</strong> 32 GB ≈ 33,554,432 KB.</li><li><strong>Reserved for Threads (1/8th):</strong> ≈ 4,194,304 KB.</li><li><strong>Kernel Stack Size:</strong> On x86_64, each thread gets a <strong>16 KB</strong> stack.</li></ul><blockquote>threads-max = 33,554,432 / (16 * 8) =&gt; <strong>262144</strong></blockquote><h4>Useful Commands</h4><p><strong>Max threads</strong> -&gt; cat /proc/sys/kernel/threads-max <em># e.g., 262144</em></p><p><strong>Max number of user process</strong> -&gt; ulimit -u <em># e.g., 126723</em></p><p><strong>Max stack size</strong> -&gt; ulimit -s <em># e.g., 8192 (in KB = 8 MB)</em></p><p><strong>Next Blog</strong></p><ul><li><a href="https://medium.com/@sridhar-sp/from-single-core-to-coroutines-bad184b17c8d">From Single Core to Coroutines</a></li><li><a href="https://github.com/sponsors/sridhar-sp">Sponsor @sridhar-sp on GitHub Sponsors</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=213992f8b2d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Needs More Than Just a Model: The Missing Role of Context, Orchestration, and Agents]]></title>
            <link>https://medium.com/@sridhar-sp/ai-needs-more-than-just-a-model-the-missing-role-of-context-orchestration-and-agents-7cd894ac4963?source=rss-8b095914072e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cd894ac4963</guid>
            <category><![CDATA[ai-orchestration]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[ai-automation]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[sridhar subramaniam]]></dc:creator>
            <pubDate>Sun, 23 Mar 2025 16:03:53 GMT</pubDate>
            <atom:updated>2026-05-27T12:04:41.702Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>AI Needs More Than Just a Model: The Missing Role of Context, Orchestration, and Agents</strong></p><p>Solving the AI Puzzle : Why External Context, Orchestration, and Agents Are Key to Intelligence</p><h3><strong>Disclaimer:</strong></h3><p><em>This blog is intended as a beginner-friendly guide to AI, specifically focusing on why Large Language Models (LLMs) should interact with agents to solve any AI query.</em></p><p>It <strong>does not</strong> <strong>cover</strong> advanced topics such as <strong>training</strong>, <strong>fine-tuning</strong>, or <strong>building LLMs </strong>from scratch because, at the time of writing, I am not deeply familiar with these areas. However, my experience comes from building an <strong>in-house orchestration system</strong>, which serves as the central component for facilitating communication between different AI components to solve any AI query. This system routes requests from input agents to classifiers and further to specific agents and tools, ultimately generating a response.</p><p><em>The goal is to introduce key concepts, </em><strong><em>terminology</em></strong><em>, and </em><strong><em>importance</em></strong><em> of </em><strong><em>Agents</em></strong><em> and the need for </em><strong><em>Orchestration</em></strong><em>.</em></p><p><strong>Target Audience:</strong></p><ul><li><strong>Beginners in AI</strong> who are exploring concepts like LLMs, agents, and orchestration.</li><li><strong>Developers from Non-AI Domain &amp; Enthusiasts</strong> looking to understand how AI models interact with real-world systems.</li><li><strong>Product Managers</strong> seeking high-level insights without deep technical details.</li></ul><h3>Analogy</h3><p>If we think of the <strong>human brain</strong> as an <strong>AI model</strong> (e.g., an LLM), then the <strong>hands</strong>, <strong>vocal cords</strong>, <strong>eyes</strong>, etc. would be its <strong>agents</strong>.</p><p>In humans, the brain processes sensory inputs and issues commands to physical agents (e.g., muscles). Here’s a simplified analogy:</p><ol><li>Your <strong>retina</strong> <strong>captures visual data</strong> of a ball coming toward you. The <strong>retina</strong> <strong>acts</strong> as an <strong>input agent</strong>, sending this data to the brain for processing.</li><li>Your brain analyzes the visual input and decides that you need to catch the ball. The <strong>brain</strong> functions as the <strong>LLM</strong> in this analogy.</li><li>The brain sends a signal to your hands to catch the ball. Your <strong>hands</strong> <strong>serve</strong> as the <strong>output agent</strong>, executing the action.</li></ol><p>If the brain (LLM) is trained properly, it instructs your hands to act correctly. However, if the training is insufficient, it might make an incorrect decision, such as instructing your eyes to close instead of catching the ball, leaving you vulnerable to an accident.</p><p><strong>AI (LLM) can process input, reason with it,</strong> and <strong>generate outputs</strong>, much <strong>like</strong> the <strong>brain processes sensory data and makes decisions</strong>. However, just as the <strong>brain requires physical agents</strong> like hands to interact with the environment, <strong>LLMs require agents</strong> to bridge the<strong> gap between reasoning and action</strong>.</p><p>Assume we use <strong>LLaMA 3.2</strong> as the LLM. Our primary <strong>input</strong> and <strong>output</strong> type is <strong>text</strong>, which makes interaction straightforward. While this works well for text-based outputs like answering questions, it doesn’t suffice for all use cases. For instance, text output is suitable when we only want an answer, but if we need to perform an action (e.g., sending an email, opening a file), the LLM cannot handle this because its sole responsibility is to generate text-based outputs. It has no inherent capability to perform actions or interact with the physical or digital world.</p><h3>Importance of Agents in AI</h3><h4>What are Agents</h4><p>From our earlier analogy, we assumed that our hands and eyes are agents in the physical world. In the digital world, we call the <strong>software component an agent</strong>; an agent is anything that can <strong>enhance</strong> your <strong>LLM</strong> to <strong>read</strong> its <strong>environment</strong>, and it can <strong>provide</strong> some <strong>actionable</strong> <strong>output</strong> from the <strong>LLM response</strong>.</p><h4>Can LLM Directly Call Agents?</h4><p>At present, <strong>LLMs cannot directly perform actions</strong>. They can:</p><p>1. Understand the input.<br>2. Provide reasoning and structured outputs.</p><p>However, <strong>LLM</strong> can <strong>instruct</strong> at best <strong>what should happen</strong> but <strong>cannot</strong> interact with the environment directly to<strong> perform those actions</strong>. For instance:</p><ul><li>An <strong>LLM</strong> <strong>can generate an HTML</strong> response but<strong> cannot open a browser</strong> to display it.</li><li>It can suggest sending an email but cannot send it.</li></ul><p>To bridge this gap, we need <strong>output agents</strong>. These agents read the LLM’s output and perform the necessary actions.</p><p><strong>Example: Output Agent</strong></p><p>If the LLM generates an HTML response, an <strong>output agent</strong> can:</p><ul><li>Open a web browser or embed a browser within an application.</li><li>Render the HTML content for the user to view.</li></ul><h3>How Agents Extend the Capabilities of LLMs</h3><p>Agents serve as intermediaries that interact with the LLM to sense the environment or execute actions.</p><p>To make the LLM’s outputs actionable, we need to <strong>augment the system with agents</strong> that can process inputs going into the LLM and/or process output from the LLM to make it perform any actions.</p><p>Let’s consider we are going to create an <strong>agent-based system</strong> that leverages an LLM to function as a <strong>humorous AI assistant</strong>.</p><p>In this setup, we define two key agents: <strong>the Input Agent and the Output Agent</strong>.</p><h4>Flow of Request Handling</h4><ol><li><strong>User submits a query.</strong></li><li><strong>The Input Agent receives the query, appends a system prompt</strong>, and forwards it to the LLM.</li><li><strong>The LLM processes the prompt, understands the context</strong>, and generates a response accordingly.</li><li><strong>The Output Agent, which understands the LLM’s response format, parses it</strong> and executes the necessary actions — such as rendering the output, speaking it aloud, or performing other predefined tasks.</li></ol><blockquote>User → Input Agent → LLM → Output Agent</blockquote><p><strong>Example:</strong></p><p>Let’s consider an example where we instruct the LLM to entertain the user with a joke and format the response in HTML:</p><ul><li><strong>System Prompt:</strong> <em>“You are a funny AI. Your job is to entertain users. Make sure your responses are in HTML format with inbuilt styles.”</em></li><li><strong>Query:</strong> “Tell me a joke.”</li></ul><p><strong>Input to LLM = </strong>“<em>System Prompt + Query</em>”</p><p>The user submits the “<em>Tell me a joke</em>” query, Input Agents creates a Prompt to LLM by appending the “<em>System Prompt with the User Query.</em>”</p><p><strong>Expected Output from LLM:</strong></p><pre>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;body style=&quot;font-family: Arial; color: blue;&quot;&gt;<br>    &lt;p&gt;Why don&#39;t scientists trust atoms? Because they make up everything!&lt;/p&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>The LLM successfully generates the output, but displaying it as a webpage or further acting on this HTML requires an <strong>output agent</strong>.</p><p>The output agent we created recognizes the <strong>HTML format</strong> in the response. thus rendering the output in a web browser.</p><p><strong>What we discussed so far is a simple agent system where each agent is hardwired to interact with the LLM in a predefined way. While this setup works for limited use cases, it becomes impractical as we introduce more agents and tasks.</strong></p><p>For example:</p><ul><li>What if we want to <strong>add a new agent</strong> that performs speech synthesis?</li><li>What if <strong>multiple agents need to work together dynamically</strong>, rather than following a fixed sequence?</li><li>What if we need to <strong>support multiple LLMs</strong> based on different tasks?</li><li>How do we manage interdependencies between agents efficiently?</li></ul><p>A manually hardcoded agent system is <strong>rigid and difficult to scale</strong>. Each new agent requires manual integration, and there’s no flexibility in execution. To build <strong>truly scalable AI applications</strong>, we need a <strong>dynamic system that can decide which agents to use, route tasks efficiently, and adapt to new capabilities, </strong>all without modifying the entire workflow.</p><blockquote>This is where <strong>Orchestration</strong> comes in, acting as the <strong>brain of the system</strong>, intelligently managing agents, LLM interactions, and task execution.</blockquote><h3>The Need for an Orchestrator</h3><p>Agents play a crucial role in AI systems by extending the capabilities of LLMs. However, since LLMs <strong>cannot directly call agents</strong>, we need a central component, an <strong>Orchestrator</strong> that connects the LLM with the required <strong>context and agents</strong> to complete a task.</p><h4><strong>List of Components in the </strong>Orchestrator System</h4><p>Assume we are going to create an<strong> orchestrator system </strong>that has the below components:</p><ol><li><strong>Input Client: </strong>Sends user queries to the Orchestrator.</li><li><strong>Agents: </strong>Responsible for different tasks, categorized as:</li></ol><ul><li><strong>Classifier Agent: </strong>Determines the type of request and decides which agent should handle it.</li><li><strong>Intermediate Agent</strong>: Performs predefined tasks.</li></ul><p>3.<strong> LLM: </strong>Processes input queries and helps in decision-making.</p><p>The <strong>Orchestrator</strong> itself runs as a <strong>daemon process</strong>, exposing APIs that allow input clients, agents, and the LLM to <strong>register and interact</strong> within the ecosystem.</p><p>In this system, we assume:</p><ul><li><strong>Multiple input clients and agents</strong> can register.</li><li><strong>Only one LLM</strong> can be registered at a time.</li></ul><h4>Registration Process</h4><ul><li><strong>Input Clients</strong> register with a unique ID so that the Orchestrator knows where to send responses once the request is fulfilled.</li><li><strong>LLM</strong> is also registered, so agents and input clients can access it via the Orchestrator when needed.</li><li><strong>Agents</strong> register with:<br>- <strong>A unique ID</strong><br>- <strong>A description</strong> of the agent role<br>- <strong>An input schema</strong> specifying what kind of input agent expect to perform predefined task<br>- <strong>An output schema</strong> defining what agent will return after processing</li></ul><p><strong>This metadata allows the LLM to determine whether the system has the necessary capability to process a given request.</strong></p><h3>Example Query Flow</h3><h4><strong>User Query:</strong></h4><p><em>“Take a snapshot from the dashboard camera, merge it with a selfie from the interior camera, and send it to Sridhar’s email.”</em></p><h4><strong>Agents &amp; Their Responsibilities</strong></h4><p><strong>[1] Camera Agent</strong></p><ul><li><strong>Role:</strong> Captures snapshots from either the dashboard or interior camera.</li><li><strong>Description:</strong> “I’m a Camera Agent. I can take snapshots from the dashboard or interior camera.”</li><li><strong>Input Schema:</strong></li></ul><pre>{<br>  &quot;takePicFromDashboard&quot;: bool,<br>  &quot;takePicFromInterior&quot;: bool<br>}</pre><ul><li><strong>Output Schema:</strong></li></ul><pre>{<br>  &quot;dashboardPicPath&quot;: &quot;string|null&quot;,<br>  &quot;interiorPicPath&quot;: &quot;string|null&quot;<br>}</pre><p><strong>[2] Photo Editor Agent</strong></p><ul><li><strong>Role:</strong> Creates a collage from multiple photos.</li><li><strong>Description:</strong> “I’m a Photo Editor Agent. I can create a collage from multiple images.”</li><li><strong>Input Schema:</strong></li></ul><pre>{<br>  &quot;picPaths&quot;: [&quot;string&quot;]<br>}</pre><ul><li><strong>Output Schema:</strong></li></ul><pre>{<br>  &quot;collagePicPath&quot;: &quot;string|null&quot;<br>}</pre><p><strong>[3] Email Agent</strong></p><ul><li><strong>Role:</strong> Sends an email with multimedia attachments.</li><li><strong>Description: </strong>“I’m an Email Agent. I can query user contacts, accept multimedia content, and send an email.”</li><li><strong>Input Schema:</strong></li></ul><pre>{<br>  &quot;emailSender&quot;: &quot;string&quot;,<br>  &quot;content&quot;: &quot;string&quot;,<br>  &quot;mimeType&quot;: &quot;string&quot;<br>}</pre><ul><li><strong>Output Schema:</strong></li></ul><pre>{<br>  &quot;isEmailSent&quot;: bool<br>}</pre><h4>How the Orchestrator Uses LLM to Execute the Plan</h4><p>When the user submits a query, the Orchestrator sends it to the LLM along with the list of registered agent descriptions.</p><p>Example LLM Prompt to Generate an Execution Plan</p><pre>I want you to act as a planner. Given a user query, devise a plan to execute it.<br><br>You can find the list of attached agents to understand the system&#39;s capabilities.<br><br>Agent descriptions:<br>[  <br>  /* All agent descriptions will be added here */  <br>]<br><br>Input Query: &quot;/* Replace user query here */&quot;<br><br>Output Format:<br>[<br>  {<br>    &quot;agentName&quot;: &quot;string&quot;,<br>    &quot;agentParam&quot;: { /* The input schema expected by the agent */ }<br>  },<br>  {<br>    &quot;agentName&quot;: &quot;string&quot;,<br>    &quot;agentParam&quot;: { /* The input schema expected by the agent */ }<br>  }<br>]</pre><p>This allows the LLM to analyze the system’s capabilities and generate an execution plan.</p><p>Since the Orchestrator understands the LLM’s structured response, it carefully executes the agents in the correct order to fulfill the request.</p><h4>Final Execution Flow</h4><blockquote>Input Client → Orchestrator → LLM → Camera Agent → Photo Editor Agent → Email Agent → (Optional: LLM Summarizes Response)</blockquote><blockquote>As AI systems evolve, orchestrators will become even more essential in bridging the gap between reasoning and action. But will AI systems ever replace human roles entirely?</blockquote><h3>Will AI Replace Humans?</h3><p>I see <strong>two major work streams</strong> emerging in AI:</p><ol><li><strong>Model Development</strong>: Engineers and researchers focused on building more efficient and powerful AI models.</li><li><strong>Agent &amp; Orchestration Systems</strong>: People working on AI agents, orchestration, and external context integration, which often requires domain-specific knowledge.</li></ol><p>Let’s say, we would like to build a <strong>video logging system which would be mounted on a car dashboard</strong>, an AI agent might be responsible for:</p><ul><li>Periodically capturing photo feeds.</li><li>Geo-tagging them with location data.</li><li>And converting the data into embeddings for an LLM to process.</li></ul><p>In this case, the agent must <strong>understand the domain</strong>, including <strong>how to interact with the camera, read GPS data, and structure the output</strong> for further AI-driven analysis. This is where human expertise in <strong>software, hardware, and system integration</strong> remains essential.</p><h4>AI’s Role in the Workforce</h4><p>AI is already transforming the workforce by automating mundane and repetitive tasks. However, <strong>AI is not yet at a stage where it can function independently, </strong>for at least the next 5–10 years, human involvement will be crucial in guiding AI systems, making them more useful, adaptable, and safe.</p><p>For instance, while AI can generate code, we are still far from <strong>an AI-driven system that can write, deploy, and manage software autonomously</strong>, such as using AWS APIs to deploy a new system without any human intervention. <strong>Until AI can reliably handle real-world complexity, human oversight will be crucial.</strong></p><h3>Summary</h3><p>To ensure scalability, an <strong>Orchestrator</strong> system is essential. It seamlessly integrates various agents, classifiers, and LLMs, efficiently managing request routing, coordinating multiple agents, and utilizing the LLM at different stages of the workflow to accomplish a desired task.</p><p>While there are open-source agent orchestration systems available, I haven’t explored them yet. For our specific use case, we built a <strong>custom Orchestrator</strong> tailored to our requirements. Once I’ve had the opportunity to evaluate other solutions, I’ll be able to provide more insights into the existing open-source options.</p><p><a href="https://github.com/sponsors/sridhar-sp">Sponsor @sridhar-sp on GitHub Sponsors</a></p><h4>Annexure</h4><p><strong>PS:</strong> <em>I used ChatGPT and QuillBot’s grammar check to refine my writing.</em></p><p><a href="https://quillbot.com/grammar-check">https://quillbot.com/grammar-check</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cd894ac4963" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Android Testing: Building Reliable Apps with Confidence (Part 3/3)]]></title>
            <link>https://medium.com/@sridhar-sp/getting-started-with-android-testing-building-reliable-apps-with-confidence-part-3-3-6022a55c5a2d?source=rss-8b095914072e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6022a55c5a2d</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[integration-testing]]></category>
            <category><![CDATA[android-testing]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[sridhar subramaniam]]></dc:creator>
            <pubDate>Mon, 06 Jan 2025 15:48:50 GMT</pubDate>
            <atom:updated>2026-05-27T12:05:11.682Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn the Fundamentals of Android Testing, One Step at a Time (Part 3/3)</p><h3>Target Audience for This Blog</h3><p>This blog covers the basics of testing in Android, providing insights into setup, dependencies, and an introduction to different types of tests. It is designed to help beginners understand the fundamentals of Android testing and how various tests are implemented.</p><p><strong><em>Previous Article</em></strong></p><p><a href="https://medium.com/@sridhar-sp/getting-started-with-android-testing-building-reliable-apps-with-confidence-ed18539d856b">Getting Started with Android Testing: Building Reliable Apps with Confidence (Part 2/3)</a></p><h3>Integration testing</h3><p>Integration testing typically involves testing the interactions between different components or modules of an application.</p><p>During these tests, we can visually observe the app launching, with all the interactions specified in the code happening in real time.</p><p>However, there’s an alternative approach that leverages GradleManagedDevices to run integration tests. This method skips the UI preview and executes the tests on a configured virtual or physical device. More details on this approach are provided in the next section.</p><h4>Integration Testing Frameworks</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zFkhg-UHaPEgEU4-9RT9Fg.png" /></figure><p>The following test cases, written for RobolectricTestRunner and AndroidJUnitRunner, appear similar to the Compose UI Unit Test code snippet. This is because the androidx.compose.ui.test.junit4 library provides test implementations for both JVM and Android. Using the same interfaces, tests can run on either runtime. The appropriate implementation is selected at runtime based on the configured test runner.</p><p>The androidx.compose.ui.test.junit4 module provides the ComposeTestRule and its Android-specific implementation, AndroidComposeTestRule. These rules allow you to set Compose content or access the activity. You can construct these rules using factory functions: createComposeRule for general use or createAndroidComposeRule if activity access is required.</p><h3>Robolectric</h3><p>In this test, we are verifying the behavior of the <strong>Login</strong> composable screen by ensuring that the login button is enabled only when the inputs provided by the user are valid.</p><ol><li><strong>Initial State Validation:</strong> The test confirms that the login button is initially disabled when no inputs are provided.</li><li><strong>Partial Input Validation:</strong> The test simulates entering invalid email and password combinations step-by-step to ensure that the button remains disabled until all conditions for validity are met.</li><li><strong>Valid Input Validation:</strong> Finally, the test validates that the login button becomes enabled only when both the email and password meet the required validation criteria (a valid email format and a password of sufficient length).</li></ol><p>This test ensures that the <strong>Login</strong> composable correctly enforces input validation and enables the login button only under valid conditions.</p><h4>System Under Test</h4><pre>@Composable<br>fun Login(onSuccess: (email: Email) -&gt; Unit, viewModel: LoginViewModel = hiltViewModel()) {<br><br>    LaunchedEffect(key1 = viewModel.loginState, block = {<br>        if (viewModel.loginState == LoginState.LoginSuccess) onSuccess(viewModel.email)<br>    })<br><br>    Column {<br>        Text(text = stringResource(id = R.string.login))<br><br>        EmailInput(modifier = Modifier<br>            .semantics { testTagsAsResourceId = true;testTag = &quot;emailInput&quot; }<br>            .testTag(&quot;emailInput&quot;)<br>            .fillMaxWidth(),<br>            value = viewModel.email.value ?: &quot;&quot;,<br>            isEnabled = viewModel.loginState !== LoginState.InProgress,<br>            onValueChange = viewModel::updateEmail)<br><br>        PasswordInput(modifier = Modifier<br>            .semantics { testTagsAsResourceId = true;testTag = &quot;passwordInput&quot; }<br>            .fillMaxWidth(),<br>            value = viewModel.password.value ?: &quot;&quot;,<br>            isEnabled = viewModel.loginState !== LoginState.InProgress,<br>            onValueChange = viewModel::updatePassword)<br><br>        if (viewModel.loginState === LoginState.LoginPending) {<br>            PrimaryButton(modifier = Modifier<br>                .semantics { testTagsAsResourceId = true;testTag = &quot;loginButton&quot; }<br>                .fillMaxWidth(),<br>                text = stringResource(id = R.string.login),<br>                enabled = viewModel.isLoginButtonEnabled,<br>                onClick = viewModel::login)<br>        }<br><br>        if (viewModel.loginState === LoginState.InProgress) {<br>            CircularProgressIndicator(<br>                modifier = Modifier<br>                    .semantics { testTagsAsResourceId = true;testTag = &quot;progressLoader&quot; }<br>                    .align(Alignment.CenterHorizontally)<br>            )<br>        }<br>    }<br>}</pre><h4>Test</h4><pre>class LoginKtTest {<br><br>  @get:Rule<br>  val composeRule = createComposeRule()<br><br>  @Test<br>  fun shouldEnableButtonOnlyWhenInputsAreValid() {<br><br>    val loginUseCase = mockk&lt;LoginUseCaseImpl&gt;(relaxed = true)<br>    val loginViewModel = LoginViewModel(loginUseCase)<br><br>    coEvery { loginUseCase.login(any(), any()) } returns Unit<br><br>    with(composeRule) {<br>      setContent { Login(onSuccess = {}, viewModel = loginViewModel) }<br>      // Initial State Validation  <br>      onNodeWithTag(&quot;loginButton&quot;).assertIsNotEnabled()<br><br>      // Partial Input Validation<br>      onNodeWithTag(&quot;emailInput&quot;).performTextInput(&quot;abcd&quot;)<br>      onNodeWithTag(&quot;loginButton&quot;).assertIsNotEnabled()<br><br>      // Partial Input Validation  <br>      onNodeWithTag(&quot;emailInput&quot;).performTextInput(&quot;abcd@gmail.com&quot;)<br>      onNodeWithTag(&quot;loginButton&quot;).assertIsNotEnabled()<br><br>      // Partial Input Validation  <br>      onNodeWithTag(&quot;passwordInput&quot;).performTextInput(&quot;12&quot;)<br>      onNodeWithTag(&quot;loginButton&quot;).assertIsNotEnabled()<br><br>      // Valid Input Validation  <br>      onNodeWithTag(&quot;passwordInput&quot;).performTextInput(&quot;12345&quot;)<br>      onNodeWithTag(&quot;loginButton&quot;).assertIsEnabled()<br>    }<br>  }<br>}</pre><h4>Dependencies</h4><pre>// Allows us to create and configure mock objects, stub methods, verify method invocations, and more<br>androidTestImplementation(&quot;io.mockk:mockk-agent:1.13.5&quot;)<br>androidTestImplementation(&quot;io.mockk:mockk-android:1.13.5&quot;)<br>androidTestImplementation(&quot;org.mockito.kotlin:mockito-kotlin:5.4.0&quot;)<br><br>// Assertion library<br>androidTestImplementation(&quot;com.google.truth:truth:1.1.4&quot;)<br><br>// Needed for createComposeRule , createAndroidComposeRule and other rules used to perform UI test<br>androidTestImplementation(&quot;androidx.compose.ui:ui-test-junit4:$compose_version&quot;) // used with AndroidTestRunner to run ui test on virtual/physical device.<br><br>// Required to add androidx.activity.ComponentActivity to test manifest.<br>// Needed for createComposeRule(), but not for createAndroidComposeRule&lt;YourActivity&gt;():<br>debugImplementation(&quot;androidx.compose.ui:ui-test-manifest:$compose_version&quot;)</pre><h4>Setup</h4><p>Create a app/src/test/resources/robolectric.properties file and define the robolectric properties.</p><pre>instrumentedPackages=androidx.loader.content<br>application=dagger.hilt.android.testing.HiltTestApplication<br>sdk=29</pre><p><a href="https://github.com/sridhar-sp/android-test/blob/main/docs/LoginTest.gif"><strong>See in action</strong></a></p><h3>Android JUnit test</h3><p>AndroidJUnitRunner is a test runner which lets us run the test on android virtual/physical/GradleManaged devices, including those using the Espresso, UI Automator, and Compose testing frameworks.</p><h3>System Under Test</h3><p>We have two composable screens: LoginScreen and ProfileScreen, both inside <a href="https://github.com/sridhar-sp/android-test/blob/main/app/src/main/kotlin/com/gandiva/android/sample/presentation/ui/main/MainScreen.kt">MainScreen</a>.</p><p>The LoginScreen has email and password fields with a submit button. <br>Pressing the submit button navigates to the ProfileScreen, which displays a greeting message with the user’s email ID.</p><h4>Test</h4><pre>@HiltAndroidTest<br>class MainScreenTest {<br><br>    @get:Rule(order = 0)<br>    val hiltAndroidRule = HiltAndroidRule(this)<br><br>    /**<br>     * Need a activity that annotated with @AndroidEntryPoint. and it has to be registered in manifest.<br>     * Add comment why we used createAndroidComposeRule instead of composeTestRule<br>     */<br>    @get:Rule(order = 1)<br>    val androidComposeRule = createAndroidComposeRule&lt;DummyTestActivity&gt;()<br><br>    @Test<br>    fun shouldSuccessfullyLaunchProfileScreenWithEmailPostLogin() {<br><br>        with(androidComposeRule) {<br>            setContent { MainScreen() }<br><br>            onNodeWithTag(&quot;emailInput&quot;).performTextInput(&quot;abc@gmail.com&quot;)<br>            onNodeWithTag(&quot;passwordInput&quot;).performTextInput(&quot;12345&quot;)<br>            onNodeWithTag(&quot;loginButton&quot;).performClick()<br><br>            waitUntil(2500L) {<br>                onAllNodesWithTag(&quot;welcomeMessageText&quot;).fetchSemanticsNodes().isNotEmpty()<br>            }<br><br>            onNodeWithTag(&quot;welcomeMessageText&quot;).assertTextEquals(&quot;Email as explicit argument abc@gmail.com&quot;)<br>            onNodeWithTag(&quot;welcomeMessageText2&quot;)<br>                .assertTextEquals(&quot;Email from saved state handle abc@gmail.com&quot;)<br><br>            waitForIdle()<br>        }<br>    }<br>}</pre><h4>Dependencies</h4><pre>// Used to create AndroidHiltTestRunner from AndroidJUnitRunner<br>androidTestImplementation(&quot;androidx.test:runner:1.6.2&quot;)</pre><h4>Setup</h4><pre>android {<br><br>  defaultConfig {<br>    // testInstrumentationRunner = &quot;androidx.test.runner.AndroidJUnitRunner&quot;<br><br>    // If we are using Hilt we can extend the AndroidJUnitRunner and pass the HiltTestApplication as application component.<br>    testInstrumentationRunner = &quot;com.gandiva.android.sample.AndroidHiltTestRunner&quot;<br>  }<br>}</pre><ul><li>Place AndroidHiltTestRunner file inside app/src/androidTest/java/../AndroidHiltTestRunner.kt</li></ul><pre>class AndroidHiltTestRunner : AndroidJUnitRunner() {<br>  override fun newApplication(cl: ClassLoader?, className: String?, context: Context?): Application {<br>    return super.newApplication(cl, HiltTestApplication::class.java.name, context)<br>  }<br>}</pre><p><a href="https://github.com/sridhar-sp/android-test/blob/main/docs/MainScreenTest.gif"><strong>See in action</strong></a></p><h3>UI Automator</h3><p>UI Automator is a UI testing framework designed for cross-app functional UI testing, allowing interaction with both system and installed apps. Unlike frameworks that are limited to the app under test, UI Automator provides a wide range of APIs to interact with the entire device.</p><p>This enables true cross-app functional testing, such as opening the device settings, disabling the network, and then launching your app to verify how it handles a no-network condition.</p><p>With UI Automator, you can easily locate UI components using convenient descriptors like the text displayed on the component or its content description, making test scripts more intuitive and readable.</p><h4>System Under Test</h4><p>We use an Android device as the system under test. The process begins by launching the home intent, bringing the device to the home screen. Once the home app is launched, we proceed to open our app for testing.</p><p>The test scenario remains the same: we navigate to the LoginScreen, enter the email and password, and press the submit button. Upon successful submission, the app navigates to the ProfileScreen, where the user is greeted with their email ID.</p><h4>Test</h4><pre>private const val BASIC_SAMPLE_PACKAGE = &quot;com.gandiva.android.sample&quot;<br>private const val LAUNCH_TIMEOUT = 5000L<br><br>@HiltAndroidTest<br>class LoginJourneyTest {<br><br>    private lateinit var device: UiDevice<br><br>    @get:Rule<br>    val hiltAndroidRule = HiltAndroidRule(this)<br><br>    @Before<br>    fun startMainActivityFromHomeScreen() {<br>        // Initialize UiDevice instance<br>        device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())<br><br>        // Start from the home screen<br>        device.pressHome()<br><br>        // Wait for launcher<br>        val launcherPackage: String = device.launcherPackageName<br>        MatcherAssert.assertThat(launcherPackage, CoreMatchers.notNullValue())<br>        device.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT)<br><br>        // Launch the app<br>        val context = ApplicationProvider.getApplicationContext&lt;Context&gt;()<br>        val intent = context.packageManager.getLaunchIntentForPackage(BASIC_SAMPLE_PACKAGE)<br>            ?.apply { addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK) }<br>        context.startActivity(intent)<br><br>        // Wait for the app to appear<br>        device.wait(Until.hasObject(By.pkg(BASIC_SAMPLE_PACKAGE).depth(0)), LAUNCH_TIMEOUT)<br>    }<br><br><br>    @Test<br>    fun shouldLaunchProfileScreenWhenLoginIsSuccess() {<br>        device.enterTextOnFieldWithId(&quot;emailInput&quot;, &quot;hello@gmail.com&quot;)<br>        device.enterTextOnFieldWithId(&quot;passwordInput&quot;, &quot;123456&quot;)<br><br>        device.wait(Until.hasObject(By.res(&quot;loginButton&quot;).enabled(true)), 1500L)<br>        assertThat(device.findObject(By.res(&quot;loginButton&quot;)).isEnabled).isEqualTo(true)<br><br>        device.clickFieldWithId(&quot;loginButton&quot;)<br><br>        device.wait(Until.hasObject(By.res(&quot;hasObject&quot;)), 3000L)<br><br>        assertThat(device.textFromFieldWithId(&quot;welcomeMessageText&quot;))<br>            .isEqualTo(&quot;Email as explicit argument hello@gmail.com&quot;)<br>        assertThat(device.textFromFieldWithId(&quot;welcomeMessageText2&quot;))<br>            .isEqualTo(&quot;Email from saved state handle hello@gmail.com&quot;)<br><br>        device.waitForIdle()<br>    }<br>}</pre><h4>Dependencies</h4><pre>// To perform UI automation test.<br>androidTestImplementation(&quot;androidx.test.uiautomator:uiautomator:2.3.0&quot;)</pre><h4>Command</h4><ul><li>The command remains the same for Robolectric, AndroidJUnit, and UI Automator tests.</li></ul><pre>./gradlew connectedAndroidTest --continue</pre><p><a href="https://github.com/sridhar-sp/android-test/blob/main/docs/JourneyTest.gif"><strong>See in action</strong></a></p><h3>Gradle Managed Devices</h3><p>Gradle Managed Devices provide a way to configure virtual or physical devices directly in Gradle for running integration tests. Since the configuration is managed within Gradle, it gains full control over the device lifecycle, allowing it to start or shut down devices as needed.</p><p>Unlike standard Android Virtual Devices (AVDs) or physical devices, there won’t be any visual preview during the test run. Once the test completes, you can review the results in the reports generated in the build folder.</p><p>Gradle Managed Devices are primarily used for running automated tests at scale on various virtual devices, so the focus is on configuration details rather than a visual representation.</p><h4>Setup</h4><pre>testOptions {<br>  managedDevices {<br>    devices {<br>      create&lt;ManagedVirtualDevice&gt;(&quot;testDevice&quot;) {<br>        device = &quot;Pixel 6&quot;<br>        apiLevel = 34<br>        systemImageSource = &quot;aosp&quot;<br>      }<br>    }<br>  }<br>}</pre><h4>Command</h4><pre>./gradlew testDeviceDebugAndroidTest</pre><h3>Source Code</h3><p><a href="https://github.com/sridhar-sp/android-test">GitHub - sridhar-sp/android-test: A collection of samples to showcase various testing types that can be performed on the Android code base.</a></p><h4>Test Your Code, Rest Your Worries</h4><blockquote><em>With a sturdy suite of tests as steadfast as a fortress, developers can confidently push code even on a Friday evening and log off without a trace of worry.</em></blockquote><p><a href="https://github.com/sponsors/sridhar-sp">Sponsor @sridhar-sp on GitHub Sponsors</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6022a55c5a2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Android Testing: Building Reliable Apps with Confidence (Part 2/3)]]></title>
            <link>https://medium.com/@sridhar-sp/getting-started-with-android-testing-building-reliable-apps-with-confidence-ed18539d856b?source=rss-8b095914072e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed18539d856b</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-testing]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[sridhar subramaniam]]></dc:creator>
            <pubDate>Mon, 06 Jan 2025 13:22:30 GMT</pubDate>
            <atom:updated>2026-05-27T12:05:29.767Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn the Fundamentals of Android Testing, One Step at a Time (Part 2/3)</p><h3>Target Audience for This Blog</h3><p>This blog covers the basics of testing in Android, providing insights into setup, dependencies, and an introduction to different types of tests. It is designed to help beginners understand the fundamentals of Android testing and how various tests are implemented.</p><p><strong><em>Previous Article</em></strong></p><p><a href="https://medium.com/@sridhar-sp/getting-started-with-android-testing-building-reliable-apps-with-confidence-5bd534df54cc">Getting Started with Android Testing: Building Reliable Apps with Confidence (Part 1/3)</a></p><h3>UI Testing</h3><p>UI testing usually refers to testing the user interface by simulating user action and verifying the behavior of UI elements.</p><h4>Famous UI Testing Frameworks</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CW4FqLytCP_uwOR9qbgS_Q.png" /></figure><h3>Compose UI + Interaction Unit Test</h3><p>The Compose UI test framework allows you to verify that the behavior of your Compose code works as expected. It provides a set of testing APIs that help you find UI elements, check their attributes, and perform user actions. Using these APIs, you can mount composable content and assert expected behaviors.</p><p>The androidx.compose.ui.test.junit4 module includes a ComposeTestRule and an implementation for Android called AndroidComposeTestRule. Through this rule, you can set Compose content or access the activity. You construct the rules using factory functions, either createComposeRule or, if you need access to an activity, createAndroidComposeRule.</p><p>For Compose UI Unit Tests, you can use the RobolectricTestRunner, a JUnit Test Runner that runs test code directly on the JVM. This eliminates the need for a physical or virtual Android device, significantly speeding up test execution, ensuring consistent results, and simplifying the testing process.</p><p>However, some classes and methods from android.jar require additional configuration to function correctly. For example, accessing Android resources or using methods like Log might need adjustments to return default or mocked values. Please refer to the setup section below for the necessary configuration.</p><h3>Example</h3><p>In this test, we are verifying the behavior of the <strong>Login</strong> composable screen by ensuring that the login button is enabled only when the inputs provided by the user are valid.</p><ol><li><strong>Initial State Validation:</strong> The test confirms that the login button is initially disabled when no inputs are provided.</li><li><strong>Partial Input Validation:</strong> The test simulates entering invalid email and password combinations step-by-step to ensure that the button remains disabled until all conditions for validity are met.</li><li><strong>Valid Input Validation:</strong> Finally, the test validates that the login button becomes enabled only when both the email and password meet the required validation criteria (a valid email format and a password of sufficient length).</li></ol><p>This test ensures that the <strong>Login</strong> composable correctly enforces input validation and enables the login button only under valid conditions.</p><h4>System Under Test</h4><pre>@Composable<br>fun Login(onSuccess: (email: Email) -&gt; Unit, viewModel: LoginViewModel = hiltViewModel()) {<br><br>  LaunchedEffect(key1 = viewModel.loginState, block = {<br>    if (viewModel.loginState == LoginState.LoginSuccess) onSuccess(viewModel.email)<br>  })<br><br>  Column {<br>    Text(text = stringResource(id = R.string.login))<br><br>    EmailInput(modifier = Modifier<br>      .semantics { testTagsAsResourceId = true;testTag = &quot;emailInput&quot; }<br>      .testTag(&quot;emailInput&quot;)<br>      .fillMaxWidth(),<br>      value = viewModel.email.value ?: &quot;&quot;,<br>      isEnabled = viewModel.loginState !== LoginState.InProgress,<br>      onValueChange = viewModel::updateEmail)<br><br>    PasswordInput(modifier = Modifier<br>      .semantics { testTagsAsResourceId = true;testTag = &quot;passwordInput&quot; }<br>      .fillMaxWidth(),<br>      value = viewModel.password.value ?: &quot;&quot;,<br>      isEnabled = viewModel.loginState !== LoginState.InProgress,<br>      onValueChange = viewModel::updatePassword)<br><br>    if (viewModel.loginState === LoginState.LoginPending){<br>        PrimaryButton(modifier = Modifier<br>            .semantics { testTagsAsResourceId = true;testTag = &quot;loginButton&quot; }<br>            .fillMaxWidth(),<br>            text = stringResource(id = R.string.login),<br>            enabled = viewModel.isLoginButtonEnabled,<br>            onClick = viewModel::login)<br>    }<br><br>    if (viewModel.loginState === LoginState.InProgress){<br>        CircularProgressIndicator(<br>            modifier = Modifier<br>                .semantics { testTagsAsResourceId = true;testTag = &quot;progressLoader&quot; }<br>                .align(Alignment.CenterHorizontally)<br>        )<br>    }<br>  }<br>}</pre><h4>Test</h4><ul><li>This is a Compose UI <strong>unit test</strong> that runs on the <strong>JVM</strong>. Therefore, the code must be placed inside app/src/test/java/../LoginKtTest.kt .</li></ul><pre>@RunWith(RobolectricTestRunner::class)<br>class LoginKtTest {<br><br>  @get:Rule<br>  val composeRule = createComposeRule()<br><br>  @get:Rule<br>  var mainCoroutineRule = MainCoroutineRule()<br><br>  @Test<br>  fun shouldEnableButtonOnlyWhenInputsAreValid() {<br>    with(composeRule) {<br>      val loginUseCase = mockk&lt;LoginUseCaseImpl&gt;()<br>      val loginViewModel = LoginViewModel(loginUseCase)<br>      setContent { Login(onSuccess = {}, viewModel = loginViewModel) }<br>      onNodeWithTag(&quot;loginButton&quot;).assertIsNotEnabled()<br><br>      onNodeWithTag(&quot;emailInput&quot;).performTextInput(&quot;abcd&quot;)<br>      onNodeWithTag(&quot;loginButton&quot;).assertIsNotEnabled()<br><br>      onNodeWithTag(&quot;emailInput&quot;).performTextInput(&quot;abcd@gmail.com&quot;)<br>      onNodeWithTag(&quot;loginButton&quot;).assertIsNotEnabled()<br><br>      onNodeWithTag(&quot;passwordInput&quot;).performTextInput(&quot;12&quot;)<br>      onNodeWithTag(&quot;loginButton&quot;).assertIsNotEnabled()<br><br>      onNodeWithTag(&quot;passwordInput&quot;).performTextInput(&quot;12345&quot;)<br>      onNodeWithTag(&quot;loginButton&quot;).assertIsEnabled()<br>    }<br>  }<br>}</pre><h4>Dependencies</h4><pre>// Needed for createComposeRule , createAndroidComposeRule and other rules used to perform UI test<br>testImplementation(&quot;androidx.compose.ui:ui-test-junit4:$compose_version&quot;) // used with robolectric to run ui test on jvm<br><br>// Needed for createComposeRule(), but not for createAndroidComposeRule&lt;YourActivity&gt;():<br>debugImplementation(&quot;androidx.compose.ui:ui-test-manifest:$compose_version&quot;)<br><br>// Dependency injection for For instrumented tests on JVM<br>testImplementation(&quot;com.google.dagger:hilt-android-testing:2.49&quot;)<br>kaptTest(&quot;com.google.dagger:hilt-compiler:2.49&quot;)<br><br>// Needed to run android UI test on JVM instead of on an emulator or device<br>testImplementation(&quot;org.robolectric:robolectric:4.10.3)<br><br>// Helper for other arch dependencies, including JUnit test rules that can be used with LiveData, coroutines etc<br>testImplementation(&quot;androidx.arch.core:core-testing:2.2.0&quot;)</pre><h4>Setup</h4><pre>testOptions {<br>        unitTests {<br>            // Enables unit tests to use Android resources, assets, and manifests.<br>            isIncludeAndroidResources = true<br>            // Whether unmocked methods from android.jar should throw exceptions or return default values (i.e. zero or null).<br>            isReturnDefaultValues = true<br>        }<br>}</pre><h4>Command</h4><pre>./gradlew testDebugUnitTest</pre><h3>Source Code</h3><p><a href="https://github.com/sridhar-sp/android-test">GitHub - sridhar-sp/android-test: A collection of samples to showcase various testing types that can be performed on the Android code base.</a></p><h4>Next Article</h4><p><a href="https://medium.com/@sridhar-sp/getting-started-with-android-testing-building-reliable-apps-with-confidence-part-3-3-6022a55c5a2d">Getting Started with Android Testing: Building Reliable Apps with Confidence (Part 3/3)</a></p><h4>Test Your Code, Rest Your Worries</h4><blockquote><em>With a sturdy suite of tests as steadfast as a fortress, developers can confidently push code even on a Friday evening and log off without a trace of worry.</em></blockquote><p><a href="https://github.com/sponsors/sridhar-sp">Sponsor @sridhar-sp on GitHub Sponsors</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed18539d856b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Android Testing: Building Reliable Apps with Confidence (Part 1/3)]]></title>
            <link>https://medium.com/@sridhar-sp/getting-started-with-android-testing-building-reliable-apps-with-confidence-5bd534df54cc?source=rss-8b095914072e------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bd534df54cc</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[junit]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-testing]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[sridhar subramaniam]]></dc:creator>
            <pubDate>Sun, 05 Jan 2025 15:09:53 GMT</pubDate>
            <atom:updated>2026-05-27T12:05:50.665Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn the Fundamentals of Android Testing, One Step at a Time (Part 1/3)</h4><h3>Target Audience for This Blog</h3><p>This blog covers the basics of testing in Android, providing insights into setup, dependencies, and an introduction to different types of tests. It is designed to help beginners understand the fundamentals of Android testing and how various tests are implemented.</p><h3>Different Types of Test</h3><p>The following are the primary testing types that are commonly used in software products:</p><ul><li>Unit testing</li><li>UI testing</li><li>Integration testing</li></ul><h4>Place of Execution</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*lQGuOaO9g6zb6nw1VEpkig.jpeg" /></figure><h3>Unit Testing</h3><p>Unit testing usually refers to testing a particular unit of code in complete isolation from other components to ensure its correctness and functionality. Developers often use frameworks like Mockito to create stubs (test doubles), mocks, etc., to achieve this isolation.</p><ul><li><strong>Stub</strong>: A stub is a direct replacement for a function, interface, or abstract class (or any other dependency). It allows us to swap the original implementation with a test-specific version, often referred to as a test dummy (or test double).</li><li><strong>Mock</strong>: A mock serves as a more advanced test double for a dependency. Mocking frameworks let us actively simulate different behaviours by configuring the mock to return specific responses based on inputs or conditions. Furthermore, mocks allow us to confirm interactions by verifying the existence of a method, its number of calls, and the arguments passed during each call.</li><li><strong>Why do we need this?</strong> During testing, especially unit testing, we aim to isolate the component under test from its dependencies. This ensures that we’re testing the component alone, making the tests simpler, faster, and less error-prone. Mocking or stubbing helps us avoid injecting side effects or relying on external dependencies.</li><li><strong>Example</strong>: Imagine a ViewModel class that depends on a repository. The Repository class, in turn, makes network API calls. If we want to write a unit test for the ViewModel alone, we don’t want to incur the overhead of making actual API calls, as this can make the test error-prone due to network conditions or server response times. To avoid these side effects, we can replace the repository with a stub (test double) or a mock during the test. This ensures that we focus only on the behaviour of the ViewModel while bypassing external dependencies.</li></ul><h4>Famous Unit Testing Frameworks</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bH2ED1TMCNk-QCNrP_H4ug.jpeg" /></figure><h3>Simple Test Without Mocks</h3><p>In this test suite, we are validating the behavior of the isValid() method in the Email class. The isValid()<br> method checks whether the email provided is a valid email address or not. We are testing three key scenarios:</p><ol><li><strong>Null Email:</strong> Verifying that when the email value is⁣ null, the method returns⁣ false .</li><li><strong>Invalid Email:</strong> Checking various invalid email formats to ensure that the method correctly returns false for them (e.g., missing domain, misplaced characters).</li><li><strong>Valid Email:</strong> Confirming that the method correctly returns true for properly formatted email addresses.</li></ol><p>Each test ensures the isValid() method behaves as expected under different conditions, guaranteeing that the email validation works correctly.</p><h4>System Under Test</h4><pre>data class Email(val value: String?) : Parcelable {<br>    fun isValid(): Boolean {<br>        return if (value == null) false else PatternsCompat.EMAIL_ADDRESS.matcher(value).matches()<br>    }<br>}</pre><h4>Test</h4><pre>class EmailTest {<br><br>    @Test<br>    fun shouldReturnIsValidAsFalseWhenEmailIsNull() {<br>        Truth.assertThat(Email(null).isValid()).isFalse()<br>    }<br><br>    @Test<br>    fun shouldReturnIsValidAsFalseWhenEmailIsInvalid() {<br>        Truth.assertThat(Email(&quot;aa@.com&quot;).isValid()).isFalse()<br>        Truth.assertThat(Email(&quot;aacd@aa.com@&quot;).isValid()).isFalse()<br>        Truth.assertThat(Email(&quot;&quot;).isValid()).isFalse()<br>        Truth.assertThat(Email(&quot;@gmail.com&quot;).isValid()).isFalse()<br>    }<br><br>    @Test<br>    fun shouldReturnIsValidAsTrueWhenEmailIsValid() {<br>        Truth.assertThat(Email(&quot;abcd@domain.com&quot;).isValid()).isTrue()<br>        Truth.assertThat(Email(&quot;a@domain.in&quot;).isValid()).isTrue()<br>    }<br>}</pre><h3>Simple Test With Mocks</h3><p>In this test, we are verifying the behavior of the ProfileViewModel class, specifically the retrieval of the email address from the⁣ SavedStateHandle The test mocks the SavedStateHandle to simulate retrieving an email address from the saved state.</p><ol><li><strong>Mocking Dependencies:</strong> We use mockk to mock the SavedStateHandle and LogoutUseCase, which are dependencies in the ProfileViewModel.</li><li><strong>Testing Behavior:</strong> The mock for SavedStateHandle is configured to return a predefined email address abcd@gmail.com when the ⁣KEY_EMAIL key is accessed.</li><li><strong>Validation:</strong> After initializing the ⁣ProfileViewModel, we assert that the emailAddress property correctly retrieves the mocked email value from the SavedStateHandle .</li></ol><p>This test ensures that the ProfileViewModel correctly reads the email address from the saved state during its initialization.</p><h4>System Under Test</h4><pre>@HiltViewModel<br>class ProfileViewModel @Inject constructor(<br>  savedStateHandle: SavedStateHandle,<br>  private val logoutUseCase: LogoutUseCase<br>) : ViewModel() {<br>  val emailAddress = savedStateHandle.get&lt;String&gt;(BundleArgs.KEY_EMAIL)<br>}</pre><h4>Test</h4><pre>@Test<br>fun `should return email value from saved state handle when email address is read from viewModel`() {<br>  val savedStateHandleMock = mockk&lt;SavedStateHandle&gt;()<br>  every&lt;String?&gt; { savedStateHandleMock[BundleArgs.KEY_EMAIL] } returns &quot;abcd@gmail.com&quot;<br><br>  val logoutUseCase = mockk&lt;LogoutUseCase&gt;()<br><br>  val profileViewModel = ProfileViewModel(savedStateHandleMock, logoutUseCase)<br>  assertThat(profileViewModel.emailAddress).isEqualTo(&quot;abcd@gmail.com&quot;)<br>}</pre><h3>Test With Mocks and Stubs</h3><p>In this test, we are testing the behavior of the ProfileViewModel class when the logout function is called, ensuring that the logout process is correctly triggered and the shouldLogout state is updated.</p><p>Let me use AAA test pattern to explain the test case. AAA stands for <strong>Arrange</strong>, <strong>Act</strong>, and <strong>Assert</strong>.</p><ol><li><strong>Arrange: Mocking and Stub Dependencies:</strong> We mock the SavedStateHandle to simulate retrieving the email address from the saved state, and we stub the LogoutUseCase to simulate a successful logout without performing the actual logic.</li><li><strong>Act: Triggering Logout:</strong> The logout function is called on the ProfileViewModel, and the coroutine is run to completion using runCurrent().</li><li><strong>Assert:</strong> The test asserts that after calling logout, the shouldLogout state is updated to true and that the logout function was successfully called, as indicated by the isLogoutSuccess flag being true.</li></ol><p>This test ensures that the ProfileViewModel correctly handles the logout process, updating the appropriate states and interacting with the LogoutUseCase.</p><h4>System Under Test</h4><pre>@HiltViewModel<br>class ProfileViewModel @Inject constructor(<br>  savedStateHandle: SavedStateHandle,<br>  private val logoutUseCase: LogoutUseCase<br>) : ViewModel() {<br>  val emailAddress = savedStateHandle.get&lt;String&gt;(BundleArgs.KEY_EMAIL)<br><br>  var shouldLogout by mutableStateOf(false)<br>    private set<br><br>  fun logout() {<br>    viewModelScope.launch {<br>      logoutUseCase.logout(Email(emailAddress))<br>      shouldLogout = true<br>    }<br>  }<br>}</pre><h4>Test</h4><pre>@Test<br>fun `should call logout callback when logout button is pressed`() = runTest(testDispatcher) {<br>    Dispatchers.setMain(testDispatcher)<br>        <br>    // Arrange    <br>    val savedStateHandleMock = mockk&lt;SavedStateHandle&gt;()<br>    every&lt;String?&gt; { savedStateHandleMock[BundleArgs.KEY_EMAIL] } returns &quot;abcd@gmail.com&quot;<br><br>    var isLogoutSuccess = false<br>    val logoutStub = object : LogoutUseCase {<br>      override suspend fun logout(email: Email) {<br>        isLogoutSuccess = true<br>      }<br>    }<br>        <br>    val profileViewModel = ProfileViewModel(savedStateHandleMock, logoutStub)<br><br>    // Act    <br>    profileViewModel.logout()<br>    runCurrent()  // run current co routine to completion<br><br>    // Assert    <br>    assertThat(profileViewModel.shouldLogout).isTrue()<br>    assertThat(isLogoutSuccess).isTrue()<br>}</pre><h4>Dependencies</h4><pre>// Regular JUnit dependency<br>testImplementation(&quot;junit:junit:4.13.2&quot;)<br><br>// Assertion library<br>testImplementation(&quot;com.google.truth:truth:1.1.4&quot;)<br><br>// Allows us to create and configure mock objects, stub methods, verify method invocations, and more<br>testImplementation(&quot;io.mockk:mockk:1.13.5&quot;)</pre><h4>Command</h4><pre>./gradlew testDebugUnitTest</pre><h3>Source Code</h3><p><a href="https://github.com/sridhar-sp/android-test">GitHub - sridhar-sp/android-test: A collection of samples to showcase various testing types that can be performed on the Android code base.</a></p><h4><strong><em>Next Article</em></strong></h4><p><a href="https://medium.com/@sridhar-sp/getting-started-with-android-testing-building-reliable-apps-with-confidence-ed18539d856b">Getting Started with Android Testing: Building Reliable Apps with Confidence (Part 2/3)</a></p><h4>Test Your Code, Rest Your Worries</h4><blockquote>With a sturdy suite of tests as steadfast as a fortress, developers can confidently push code even on a Friday evening and log off without a trace of worry.</blockquote><p><a href="https://github.com/sponsors/sridhar-sp">Sponsor @sridhar-sp on GitHub Sponsors</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bd534df54cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>