<?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 Jayashree Sudalagunta on Medium]]></title>
        <description><![CDATA[Stories by Jayashree Sudalagunta on Medium]]></description>
        <link>https://medium.com/@jayashree.sudalagunta?source=rss-d949e0a7c2c0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Jayashree Sudalagunta on Medium</title>
            <link>https://medium.com/@jayashree.sudalagunta?source=rss-d949e0a7c2c0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 14:35:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jayashree.sudalagunta/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[What is ThreadPool and why do we use it?]]></title>
            <link>https://medium.com/@jayashree.sudalagunta/what-is-threadpool-and-why-do-we-use-it-b3bb18ec61df?source=rss-d949e0a7c2c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3bb18ec61df</guid>
            <category><![CDATA[threadpoolexecutor]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[threading]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <dc:creator><![CDATA[Jayashree Sudalagunta]]></dc:creator>
            <pubDate>Mon, 22 Dec 2025 03:30:14 GMT</pubDate>
            <atom:updated>2025-12-22T03:30:14.427Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t77yquPfsnHSol8baPfF_A.png" /></figure><p>As we all know, for each app at least we will have one process, and under each process we can have multiple threads. Let’s take an example: assume our app is allocated with a maximum of 50MB memory. Now consider that for every task we start a new thread — for example, downloading an image or uploading a video, which are long-running tasks.</p><p>Let’s say we have 100 such tasks, so we end up starting 100 threads. Consider that each thread takes around 512KB of memory just to start doing the task, and later it may take more memory based on the task. So if we have 100 tasks, it will take around 50MB of memory. But since our app itself is allocated only 50MB, we will end up getting an OOM (Out Of Memory) exception.</p><p>We cannot start 100 threads for 100 tasks because of OOM. Instead, we can limit the number of threads — for example, 4 threads — and these 4 threads can repeatedly take care of executing tasks in parallel, one after another. This is nothing but a <strong>ThreadPool</strong>.</p><h3>How is ThreadPool built internally?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OVQj0d8bVIt-S98Sn1dUuA.png" /></figure><p>As shown in the image, inside a ThreadPool object we will have a <strong>queue of tasks</strong>. Whenever a new task comes, we push the task into the queue. Whenever any thread becomes free, it will pick a task from the queue and finish it.</p><p>As a developer, you can decide how many threads you want at maximum in your ThreadPool. Below is how you can create a ThreadPool using five parameters:</p><pre>val threadPoolExecutor = ThreadPoolExecutor(<br>    corePoolSize = 4,<br>    maximumPoolSize = 8,<br>    keepAliveTime = 30 seconds,<br>    queueHoldingTasks = Queue(holds 10 tasks)<br>)</pre><p>Let’s consider our example where:</p><ul><li>corePoolSize = 4</li><li>maximumPoolSize = 8</li><li>keepAliveTime = 30 seconds</li><li>Queue can hold a maximum of 10 tasks</li></ul><p>Initially, the queue will be empty, which means there is no task to execute. If the queue is empty, there is no point in creating threads, so threads won’t be created.</p><p>Now, let’s say you push one task into the queue. One thread will be created in the ThreadPool and it will start executing the task. If you push a second task, a second thread will be created. Once you push 4 tasks, all 4 threads from the corePoolSize will be created and will keep executing tasks.</p><p>When you push the 5th task, it will go into the queue. Whenever any of the 4 threads becomes free, it will take the 5th task from the queue and execute it.</p><h3>CorePoolSize vs MaximumPoolSize behavior</h3><p>Now, assume all 4 threads from the corePoolSize are already executing tasks, and you push one more task into the queue. Since all core threads are busy, the task will stay in the queue. You might think that a thread from the maximumPoolSize will be created immediately, but that is not the case. Let’s understand why.</p><p>Now assume the 4 core threads are executing tasks and you push 10 more tasks into the queue. The queue can hold only 10 tasks, so now the queue is full. If you push one more task after that, this is when the extra threads from the maximumPoolSize (up to 4 more threads) will be created to execute the remaining tasks.</p><p>The threads created as part of the corePoolSize will always remain in memory. But this is not the case for the extra threads created from the maximumPoolSize. Once these extra threads finish their tasks, they will wait for new tasks for 30 seconds (the keepAliveTime). If no new task arrives within 30 seconds, these extra threads will be killed. The corePoolSize threads will remain in memory unless the ThreadPool is shut down.</p><p>If all threads are occupied and the queue is already full with 10 tasks, and you try to push one more task, then you will get a TaskRejectedException.</p><h3>One more important scenario</h3><p>Let’s say 4 threads from the corePoolSize are busy, and the queue has 10 tasks. When you try to push one more task, the maximumPoolSize threads will be created and start executing tasks.</p><p>Now assume out of the 4 extra threads from the maximumPoolSize, one thread finishes its task. You might think that this thread will immediately pick another task from the queue (since the queue still has tasks). But this assumption is wrong.</p><p>That extra thread will wait for 30 seconds (keepAliveTime). If no new task is pushed into the queue during that time, the thread will be killed. So basically, threads from the maximumPoolSize work only when the queue is full and we try to push extra tasks.</p><p>You can also build a <strong>priority queue</strong>, so that tasks are executed based on priority.</p><p><strong>Conclusion</strong></p><p>Starting a new thread for every task may look simple, but it is not a scalable solution. Creating too many threads leads to high memory usage and can easily cause OOM exceptions, especially in memory-constrained environments like Android applications.</p><p>ThreadPool helps us solve this problem by limiting the number of threads and reusing them efficiently. Instead of creating and destroying threads repeatedly, a fixed set of threads executes multiple tasks using a queue-based mechanism. This improves performance, reduces memory overhead, and gives us better control over how tasks are executed.</p><p>By properly configuring corePoolSize, maximumPoolSize, queue size, and keepAliveTime, we can handle multiple tasks efficiently while keeping the app stable. Understanding how ThreadPool works internally helps developers make better decisions and avoid common concurrency and memory-related issues.</p><p>In short, ThreadPool is a powerful and essential tool for managing background tasks in a safe, efficient, and scalable way.</p><p>Happy Learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3bb18ec61df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Android Garbage Collector: The Key to a Smoother App Experience (Part 2)]]></title>
            <link>https://medium.com/@jayashree.sudalagunta/understanding-the-android-garbage-collector-the-key-to-a-smoother-app-experience-part-2-448c38bedfaf?source=rss-d949e0a7c2c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/448c38bedfaf</guid>
            <category><![CDATA[android-memory-management]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[outofmemoryerror]]></category>
            <category><![CDATA[garbage-collector]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Jayashree Sudalagunta]]></dc:creator>
            <pubDate>Wed, 26 Nov 2025 19:01:41 GMT</pubDate>
            <atom:updated>2025-11-26T19:01:41.893Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome back to the second installment of our deep dive into Android memory management! In [Part 1], we laid the groundwork for how your app consumes memory. Today, we’re tackling the invisible force responsible for cleaning it up: the <strong>Garbage Collector (GC)</strong>, and how its operation is the root cause of many frustrating application lags.</p><h3>The Android Garbage Collector (GC) in Action</h3><p>Every Android application operates within a defined memory limit, which we call the <strong>Heap</strong>. When your app creates new objects (like an Activity or a data structure), that memory is allocated from the heap.</p><p>Let’s use a simplified example based on a <strong>50 MB</strong> heap:</p><p>Application Core 5 MB<br>Activity 1 10 MB<br>Activity 2 10 MB<br>Total Used 25 MB</p><p>Now, imagine the user navigates away from <strong>Activity 1</strong> and <strong>Activity 2</strong> and launches <strong>Activity 3 (10 MB)</strong>.</p><p>The objects for <strong>Activity 1</strong> and <strong>Activity 2</strong> are now considered “dead” or <strong>unreachable</strong> no longer being used by the active part of your app. However, the memory they used is <strong>not instantly returned to the system</strong>.</p><p>For a brief period, your memory usage might look like this:</p><ul><li>Application Core: 5 MB</li><li>Activity 3: 10 MB</li><li>Activity 1 (Dead): 10 MB</li><li>Activity 2 (Dead): 10 MB</li><li><strong>Total Used: 35 MB</strong></li></ul><p>This is where the <strong>Garbage Collector</strong> comes in.</p><h3>How the GC Cleans Up</h3><p>The Android GC (which uses a sophisticated, generational algorithm) essentially pauses the application momentarily to identify and free up unneeded memory. Conceptually, it works like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SDEXNDFoK9P8bq2RdkJi9g.png" /><figcaption>Memory allocation blocks</figcaption></figure><ol><li>It iterates through the heap’s memory blocks something like shown above image where 50 blocks for 50MB and GC will go through the all 50 blocks and checks the usage of the memory.</li><li>It determines which objects are still actively “reachable” (in use).</li><li>Any objects found to be <strong>unreachable</strong> (like the dead activities) are marked for collection.</li><li>The memory associated with these unreachable objects is freed.</li></ol><p>This process, while necessary, takes time. The bigger the heap, the longer the GC takes to complete its pass.</p><h3>Can We Manually Trigger the GC?</h3><p>You might wonder if you can just call a method to force a cleanup before things get messy.</p><p>The short answer is <strong>yes, you can request it</strong> using the System.gc() method.</p><p>However, the real answer is <strong>no, you cannot force it</strong>. Calling System.gc() is merely a <strong>request</strong> to the Android OS. The OS has its own complex internal logic to decide when to run GC—typically when memory is low (<strong>memory pressure</strong>) or when the system is idle. Your explicit call is almost always ignored.</p><h3>The Core Problem: Why Your Android App Lags</h3><p>To understand the connection between the GC and app lag, we first need to understand how smooth motion is rendered on a screen.</p><h3>Frames, FPS, and the 16 ms Budget</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e7OkwutZt1htbm0klrguuA.png" /></figure><p>What we perceive as a smooth animation or video is actually a rapid sequence of still images, or <strong>frames</strong>.</p><p>Most standard Android devices operate at <strong>60 Frames Per Second (60 FPS)</strong>. This translates to a strict time budget: for the screen to update smoothly, the operating system must draw a new frame approximately every <strong>16 milliseconds (ms) as shown in above image</strong>.</p><p>If a new frame is successfully drawn within 16ms, the motion feels smooth.</p><p>If the rendering process takes longer than 16ms, the system misses the deadline, the frame is skipped, and the user experiences a <strong>“jank”</strong> or <strong>lag</strong>.</p><h3>The Main Thread Bottleneck</h3><p>This is the critical point: the <strong>Main Thread (or UI Thread)</strong> is the <em>only</em> thread capable of drawing (rendering) the user interface.</p><p>Unfortunately, the Main Thread is also responsible for:</p><ol><li>Processing user input (clicks, swipes).</li><li>Executing all other code <em>not</em> explicitly delegated to a background thread.</li><li><strong>Crucially: Running parts of the Garbage Collector.</strong></li></ol><h4>The GC Blocking Issue</h4><p>Imagine a scenario:</p><ul><li>The Main Thread starts drawing a frame: <strong>Time taken: 14 ms</strong> (Success!)</li><li>The Main Thread is immediately forced to start a Garbage Collection cycle: <strong>Time taken: 12 ms</strong></li><li><strong>Total time for the next frame: 14ms + 12ms = 26ms</strong></li></ul><p>Since 26ms is greater than the 16ms, the next frame is dropped, and your app lags. The time the GC is running is time the actual app code is <em>not</em> running a condition often referred to as <strong>“stop-the-world”</strong> (though modern GCs reduce its impact).</p><p><strong>The takeaway: Any time the GC runs on the Main Thread, it poses a direct and immediate threat to your frame rate.</strong></p><h3>The Myth of android:largeHeap=&quot;true&quot;</h3><p>Whenever developers face an <strong>OutOfMemory (OOM) error</strong>, they often turn to the internet and find a popular but flawed “solution”: setting android:largeHeap=&quot;true&quot; in the application manifest.</p><h3>Why largeHeap Is Not the Solution</h3><p>Using android:largeHeap=&quot;true&quot; simply instructs the OS to allocate a <strong>larger maximum heap size</strong> for your app (e.g., jumping from 50 MB to 200 MB).</p><p>The flaw in this solution is revealed when the GC runs:</p><ol><li>A larger heap means <strong>more memory blocks for the GC to check</strong>.</li><li>A larger task for the GC means <strong>it will take more time to complete</strong>.</li><li>Since the GC runs on the Main Thread, <strong>a longer GC time means more frame drops and more lag</strong>.</li></ol><p>Instead of solving the OOM error, you’ve merely postponed it while simultaneously <strong>guaranteeing a slower, laggier user experience from the beginning.</strong></p><h3>Proven Strategies to Tame the GC</h3><p>The true solutions for performance lie in <strong>reducing memory pressure</strong> and <strong>offloading heavy work</strong>.</p><h3>1. Reduce GC by Reducing Memory Pressure</h3><p>The GC is primarily triggered by memory pressure (the system needing more available memory). If you constantly allocate new, short-lived objects without properly releasing references, the pressure builds, and the GC runs more often.</p><ul><li><strong>Avoid creating unnecessary objects:</strong> Reuse objects whenever possible (e.g., using object pools).</li><li><strong>Prevent memory leaks:</strong> Ensure you don’t hold onto references to dead activities, views, or contexts, especially via static variables or non-static inner classes.</li></ul><h3>2. Delegate Tasks to Background Threads</h3><p>The most immediate fix for jank is to make the Main Thread as lightweight as possible. All long-running or non-UI-related tasks <strong>must</strong> be delegated to a background thread.</p><ul><li>Network calls</li><li>Database operations</li><li>Complex calculations</li><li>Large bitmap processing</li></ul><h3>3. Embrace Multi-Process Architecture</h3><p>Android allows your application to span across multiple operating system processes. Each process has its own separate <strong>Main Thread</strong>, its own dedicated memory heap, and its own <strong>Garbage Collector</strong>.</p><p>This is a powerful technique for handling memory-intensive operations:</p><ul><li><strong>Process Isolation:</strong> You can dedicate one process entirely to background work (e.g., video downloading, heavy data syncs) and another process to the UI.</li><li><strong>GC Isolation:</strong> If the background process experiences high memory pressure and triggers a lengthy GC cycle, the Main Thread of your UI process is <strong>completely unaffected</strong>, preventing lag.</li></ul><p>You can create a new process by defining a component (like a Service or Activity) with the android:process attribute in the AndroidManifest.xml:</p><p>XML</p><pre>&lt;service<br>    android:name=&quot;com.example.HeavyDutyService&quot;<br>    android:process=&quot;:heavy_duty_process&quot;<br>/&gt;</pre><h3>4. Utilize Native Memory (C/C++)</h3><p>For exceptionally large or critical memory allocations (like large bitmaps or massive data buffers), you can write code in <strong>C or C++</strong> using the <strong>Android NDK</strong>.</p><p>Objects allocated using native code are stored in the device’s main <strong>RAM</strong>, <em>outside</em> the application’s managed heap.</p><ul><li><strong>Advantage:</strong> These objects do not contribute to heap size, which means they do not increase the GC’s workload or trigger GC cycles, eliminating associated lag.</li><li><strong>Caution:</strong> You become fully responsible for manually managing this memory. You must explicitly free it when done, or you will create a native memory leak!</li></ul><h3>🎯 Conclusion</h3><p>A smooth Android app is a quiet one. The key to excellent performance is preventing the Garbage Collector from shouting at the Main Thread. By reducing memory pressure, offloading tasks, and intelligently utilizing process isolation, you can ensure your app stays within that crucial 16ms frame budget, delivering a flawless user experience.</p><p><em>What are your biggest questions about process isolation or native memory? Let me know in the comments below!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=448c38bedfaf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memory Usage in Android — Part 1]]></title>
            <link>https://medium.com/@jayashree.sudalagunta/memory-usage-in-android-part-1-b490de780950?source=rss-d949e0a7c2c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b490de780950</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-memory-management]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[outofmemoryerror]]></category>
            <dc:creator><![CDATA[Jayashree Sudalagunta]]></dc:creator>
            <pubDate>Sun, 26 Oct 2025 07:54:09 GMT</pubDate>
            <atom:updated>2025-10-26T07:54:09.346Z</atom:updated>
            <content:encoded><![CDATA[<h3>Memory Usage in Android — Part 1</h3><p>In this part, we’ll discuss <strong>why Android apps run into OutOfMemory (OOM) issues</strong> and what really happens behind the scenes when your app consumes too much memory.</p><h4>Understanding App Memory Allocation</h4><p>Let’s take an example. Suppose you have a smartphone with <strong>3 GB of RAM</strong>. Out of this, a portion is reserved for the <strong>operating system (OS)</strong>, and the remaining is available for all the <strong>user applications</strong> combined.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SjYTx_b_kOLP2qyAw_UKTw.png" /></figure><p>Let’s assume:</p><ul><li><strong>1 GB</strong> is used by the OS.</li><li>The remaining <strong>2 GB</strong> is shared among all running apps.</li></ul><p>Now, the <strong>maximum memory limit per app</strong> is determined by the device manufacturer and can vary from one device to another.<br> For example, let’s say the manufacturer has set a <strong>192 MB limit per app</strong>.</p><p>If your app ever tries to use more than this allocated 192 MB, you’ll encounter the dreaded <strong>OutOfMemoryError</strong>.</p><h3>Key Memory Terms</h3><p>Before diving deeper, let’s understand a few common terms related to memory:</p><ul><li><strong>Max Memory (maxMemoryInMB)</strong> → The maximum memory your app can use (e.g., 192 MB).</li><li><strong>Total Memory (totalMemoryInMB)</strong> → The amount of memory currently allocated to your app by the system.</li><li><strong>Free Memory (freeMemoryInMB)</strong> → Unused memory within your app’s current allocation.</li><li><strong>Used Memory (usedMemoryInMB)</strong> → The memory currently being used by your app.</li></ul><p>For instance, when your app first launches, it might be allocated 192 MB. But if it’s only using 3 MB, the system recognizes that a large portion (189 MB) is sitting unused and could be better utilized elsewhere.</p><h3>How Android Dynamically Manages Memory</h3><p>Initially, the system doesn’t know how much memory your app will need. It assigns the <strong>maximum possible memory (192 MB in this case)</strong> to your app.</p><p>As your app starts running, the system monitors usage. If it sees that your app only uses 3 MB consistently, it will <strong>reclaim unused memory</strong> (189 MB) and <strong>reallocate it to other apps</strong> that might need it more.</p><p>Over time, the total allocated memory for your app might drop from 192 MB to, say, 8 MB.</p><p>If your app later starts consuming more memory — for example, by loading large bitmaps or creating many objects — the system may increase the memory allocation again as needed.</p><p>However, if your app suddenly needs 30 MB more memory, but the system only has 20 MB available (because other apps are using it), your app will crash with an <strong>OutOfMemoryError</strong>.</p><h3>A Simple Example</h3><p>Consider the code below, where a background thread runs a loop that adds 1,000,000 items to a list inside onCreate().</p><pre>class MainActivity : AppCompatActivity(), ComponentCallbacks2 {<br><br>    private val idList = arrayListOf&lt;Int&gt;()<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        logCurrentMemoryProfile(&quot;onCreate start&quot;)<br><br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_main)<br><br>        logCurrentMemoryProfile(&quot;onCreate after setContentView&quot;)<br><br>        Thread {<br>            Thread.sleep(10000)<br>            logCurrentMemoryProfile(&quot;onCreate end after delay&quot;)<br>        }.start()<br>    }<br><br>    fun execute(view: View) {<br>        for (i in 1..1000000) {<br>            idList.add(i)<br>        }<br>        logCurrentMemoryProfile(&quot;execute current idList size : ${idList.size}&quot;)<br>    }<br><br>}<br></pre><pre>fun logCurrentMemoryProfile(src: String) {<br>    val maxMemoryInMB = Runtime.getRuntime().maxMemory() / 1024 / 1024<br>    val totalMemoryInMB = Runtime.getRuntime().totalMemory() / 1024 / 1024<br>    val freeMemoryInMB = Runtime.getRuntime().freeMemory() / 1024 / 1024<br>    val usedMemoryInMB = totalMemoryInMB - freeMemoryInMB<br><br>    Log.d(TAG, &quot;***************************&quot;)<br>    Log.d(TAG, &quot;Start for the source: $src&quot;)<br><br>    Log.d(TAG, &quot;maxMemoryInMB : $maxMemoryInMB&quot;)<br>    Log.d(TAG, &quot;totalMemoryInMB : $totalMemoryInMB&quot;)<br>    Log.d(TAG, &quot;freeMemoryInMB : $freeMemoryInMB&quot;)<br>    Log.d(TAG, &quot;usedMemoryInMB : $usedMemoryInMB&quot;)<br><br>    Log.d(TAG, &quot;End for the source: $src&quot;)<br>    Log.d(TAG, &quot;***************************&quot;)<br>}</pre><p>When you run this code, you’ll notice that at the start, the <strong>free memory</strong> is nearly equal to the <strong>total memory</strong>. After a few seconds, the <strong>total memory</strong> reduces because the system realizes your app doesn’t need that much memory.</p><p>But as the loop continues and more items are added to the list, the system will try to allocate additional memory. If the system runs out of available space and can’t allocate more, your app will crash with an <strong>OutOfMemoryError</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ubS8g5zryFJkkWyCYlx4zg.png" /><figcaption>Log file screenshot of how memory is allocated in this case.</figcaption></figure><h3>Why This Behavior Is Helpful</h3><p>This <strong>dynamic memory management</strong> by Android is actually beneficial. It allows the system to efficiently distribute available memory among multiple apps, enabling users to <strong>run several apps in parallel</strong> without significant performance issues.</p><p>In <strong>Part 2</strong>, we’ll explore how the <strong>Garbage Collector (GC)</strong> works in Android, and how it helps manage memory by freeing up unused objects. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b490de780950" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Using Lambdas in Kotlin Can Improve Performance]]></title>
            <link>https://medium.com/@jayashree.sudalagunta/why-using-lambdas-in-kotlin-can-improve-performance-36d56098ad04?source=rss-d949e0a7c2c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/36d56098ad04</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-lambdas-explained]]></category>
            <category><![CDATA[kotlin-lambda-expression]]></category>
            <category><![CDATA[kotlin-lambdas]]></category>
            <category><![CDATA[lambda]]></category>
            <dc:creator><![CDATA[Jayashree Sudalagunta]]></dc:creator>
            <pubDate>Mon, 13 Oct 2025 02:46:18 GMT</pubDate>
            <atom:updated>2025-10-13T02:46:18.053Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>A simple yet powerful example that shows how Kotlin lambdas can save you time — literally.</strong></h4><p>When we talk about Kotlin, one of the first things developers love is <strong>lambdas</strong> — concise, expressive, and elegant.<br> But beyond the syntactic sugar, <strong>lambdas can actually help you write more efficient and performant code</strong>.</p><p>In this post, we’ll explore how a small tweak using a lambda can reduce unnecessary computation and improve runtime performance — with a real example you can test yourself.</p><p>Let’s start with a simple example:</p><pre>var debug = false<br>var nextWord = &quot;World&quot;<br><br>fun debug1(function: () -&gt; String) {<br>    if (debug) println(function())<br>}<br><br>fun debug2(value: String) {<br>    if (debug) println(value)<br>}<br><br>fun use() {<br>    debug1 { &quot;Hello $nextWord&quot; }<br>    debug2(&quot;Hello $nextWord&quot;)<br>}</pre><p>Here we have two functions: <strong>debug1</strong> and <strong>debug2</strong>.<br> Both serve the same purpose — to print a debug message when debug is true.</p><p>Now the question is:<br> <strong>Which version would you prefer to write — </strong><strong>debug1 or </strong><strong>debug2?</strong></p><p>If you’ve been coding for a while, you might lean towards debug1.<br> Let’s see why that’s the better choice.</p><p><strong>Understanding the Difference</strong></p><p>In the above example, debug is set to false.<br> That means nothing should be printed to the console.</p><p>But here’s the key point:</p><ul><li>In <strong>debug2</strong>, the string &quot;Hello $nextWord&quot; is <em>always</em> created, even if debug is false.<br> The code first concatenates the strings and <em>then</em> checks whether to print it.</li><li>In <strong>debug1</strong>, the string is created <em>only if</em> debug is true.<br> That’s because the lambda (function: () -&gt; String) won’t be invoked at all when debug is false.</li></ul><p>In simple terms, <strong>debug1 avoids unnecessary string concatenation</strong>.<br> If debugging is turned off, there’s no point wasting CPU cycles building strings that will never be printed.</p><p>This small optimization might seem trivial, but it matters — especially in performance-critical code or loops running thousands of times.</p><p><strong>Let’s Prove It with an Example</strong></p><p>We can run a small experiment to see the difference:</p><pre>import kotlin.system.measureNanoTime<br><br>fun main() {<br>    val iterations = 1_000_000<br><br>    val timeWithLambda = measureNanoTime {<br>        repeat(iterations) {<br>            debug1 { &quot;Hello $nextWord&quot; }<br>        }<br>    }<br><br>    val timeWithoutLambda = measureNanoTime {<br>        repeat(iterations) {<br>            debug2(&quot;Hello $nextWord&quot;)<br>        }<br>    }<br><br>    println(&quot;$timeWithLambda ns - debug1 (with lambda)&quot;)<br>    println(&quot;$timeWithoutLambda ns - debug2 (without lambda)&quot;)<br>}</pre><p>This code runs both functions <strong>1 million times</strong> and measures how long each approach takes.</p><p>If you execute this snippet, you’ll notice that <strong>debug2 takes more time</strong> than <strong>debug1</strong>, because debug2 performs the string concatenation on every iteration — even though debug is false.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*7LMqEnh9xtOREv_FUIInsQ.png" /><figcaption>Result of above code</figcaption></figure><p><strong>Conclusion</strong></p><p>Lambdas in Kotlin are not just a syntax sugar; they can also be a <strong>performance optimization tool</strong> in the right context.</p><p>By deferring the execution of code until it’s truly needed, lambdas help you:</p><ul><li>Avoid unnecessary computations</li><li>Reduce CPU work</li><li>Write cleaner, more efficient code</li></ul><p>So next time you’re writing debug logs or any conditional logic, think about whether a <strong>lambda</strong> could make your code both smarter and faster.</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36d56098ad04" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unveiling the Magic: How Android’s ViewModel Works Under the Hood]]></title>
            <link>https://medium.com/@jayashree.sudalagunta/unveiling-the-magic-how-androids-viewmodel-works-under-the-hood-e690afbf28be?source=rss-d949e0a7c2c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/e690afbf28be</guid>
            <category><![CDATA[viewmodel]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[viewmodelprovider]]></category>
            <category><![CDATA[viewmodelstore]]></category>
            <category><![CDATA[mvvm-architecture]]></category>
            <dc:creator><![CDATA[Jayashree Sudalagunta]]></dc:creator>
            <pubDate>Sun, 05 Oct 2025 03:02:13 GMT</pubDate>
            <atom:updated>2025-10-05T03:02:13.971Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever wondered what makes Android’s <strong>ViewModel</strong> so special? It&#39;s not just a class; it&#39;s the key to maintaining your UI&#39;s state across those dreaded <strong>configuration changes</strong>, like screen rotation.</p><p>It can feel like magic, but like all good magic, it’s just brilliant engineering. Let’s break down the logic and reveal the surprisingly simple, yet effective, pattern that powers the ViewModel. By the end, you&#39;ll know how to build your own ViewModel!</p><h3>What Problem Does ViewModel Solve?</h3><p>At its core, a <strong>ViewModel</strong> is used to <strong>hold the state of your UI</strong> and <strong>persist that data</strong> during configuration changes. The &quot;state&quot; is simply whatever data is currently visible on your screen—the text, the items in a list, or, in our example, a simple counter.</p><p>You might think, “I can already hold state with LiveData or StateFlow!&quot; And you&#39;d be right.</p><p>Let’s look at a simple example where we create our own counter ViewModel (we&#39;ll call it a regular class for now):</p><pre>class MainViewModel {<br>// Internal mutable state<br>    private val _counter: MutableLiveData&lt;Int&gt; = MutableLiveData(0)<br>// Public immutable state for observation<br>    val counter: LiveData&lt;Int&gt; = _counterfun increaseCounter() {<br>        _counter.value = _counter.value?.plus(1)<br>    }<br>}</pre><p>In your <strong>Activity</strong>, you&#39;d instantiate it and observe the changes:</p><pre>// In MainActivity&#39;s onCreate()<br>val viewModel = MainViewModel()<br>// Observe and update the UI<br>viewModel.counter.observe(this) {<br>    binding.textView.text = it.toString()<br>}<br>// Button click to update the state<br>binding.buttonClickMe.setOnClickListener {<br>    viewModel.increaseCounter()<br>}</pre><p>When you first run this code, your counter app will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3QY4yRLzjtYdXudKeCmKjQ.jpeg" /></figure><p>And after you click the “Click Me” button a few times, it updates as expected:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BdF3Pp9r0VaXE6Yb6nqtKQ.jpeg" /></figure><p>This code works perfectly… until a configuration change happens. Rotate your screen, and BAM! The counter resets to 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-5W7DUdZBJWAHjtUkXQFUg.jpeg" /></figure><p><strong>Why?</strong></p><h3>The Root Cause: Activity Lifecycle</h3><p>When a configuration change occurs (like a device rotation or language change), the <strong>Activity</strong> is destroyed and then recreated.</p><ul><li>The old <strong>Activity</strong> instance is destroyed, calling onDestroy().</li><li>A new <strong>Activity</strong> instance is created, calling onCreate().</li><li>Inside the new onCreate(), we call val viewModel = MainViewModel().</li><li>This line creates a <strong>brand new instance</strong> of our MainViewModel, and that new instance has the counter initialized back to 0.</li></ul><p>We successfully held the state <em>momentarily</em>, but we failed to <strong>persist the data</strong> across the lifecycle change.</p><h3>Step 1: Finding a Home with a Longer Life 🏡</h3><p>To overcome this, we need a place to store our ViewModel instance that has a <strong>longer lifespan than the </strong><strong>Activity</strong> itself.</p><p>Think about the components in your app:</p><ul><li><strong>Activity</strong>: Lives for the duration of its screen time (e.g., 3 minutes).</li><li><strong>Application</strong>: Lives for the entire time the user is interacting with your app (e.g., 5 minutes, until the user closes it).</li></ul><p>The <strong>Application</strong> class is the perfect candidate! Its lifecycle is guaranteed to outlive any single Activity.</p><p>Let’s ask the <strong>Application</strong> class to hold our ViewModel instances for us using a simple <strong>HashMap</strong>:</p><pre>class MainApplication : Application() {<br>// A map to store ViewModels: Key (String, e.g., &quot;MainActivity&quot;) -&gt; Value (ViewModel)<br>    private val map = HashMap&lt;String, MainViewModel&gt;()<br>    fun getViewModel(key: String): MainViewModel {<br>        // 1. Check if an instance already exists in the map<br>        if (map[key] != null) {<br>            return map[key]!!<br>        }<br>        // 2. If not, create a new one<br>        val viewModel = MainViewModel()<br>        // 3. Store the new instance in the map<br>        map[key] = viewModel<br>        return viewModel<br>    }<br>    fun clearViewModel(key: String) {<br>        map.remove(key)<br>    }<br>}</pre><p>Now, in our <strong>MainActivity</strong>, we retrieve the <strong>existing</strong> ViewModel instance from the Application class:</p><pre>// In MainActivity&#39;s onCreate()<br>// Get the application and cast it to our custom class<br>val mainApplication = application as MainApplication<br>// Request the ViewModel instance, which will either return an existing one<br>// or create a new one and store it.<br>viewModel = mainApplication.getViewModel(&quot;MainActivity&quot;)</pre><p><strong>Tada!</strong> On configuration change, the old Activity is destroyed, but the MainApplication instance remains in memory, holding our counter. The new Activity simply retrieves the existing ViewModel instance with the old, persistent data. Problem solved!<br>Now, when you click the counter a few times and then rotate your screen, the counter value persists:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_HCGCSy5xuxi83UjKmlA0w.jpeg" /></figure><h3>Step 2: Knowing When to Let Go</h3><p>Or is it? We’ve solved persistence across config changes, but we’ve introduced a new problem: <strong>memory leaks</strong> and stale data.</p><p>Consider this scenario:</p><ul><li>You are in MainActivity. The counter is 5.</li><li>You press a button to open NextActivity and you <strong>finish()</strong> the MainActivity.</li><li>You later navigate <em>back</em> to a new instance of MainActivity.</li></ul><p>Since our MainApplication is still holding the ViewModel with the key &quot;MainActivity&quot;, the counter will <strong>still be 5</strong>, even though the user started a brand-new activity. We need to <strong>clear the </strong><strong>ViewModel instance</strong> when the Activity is <strong>permanently finished</strong>.</p><p>A logical place to clear it is in onDestroy():</p><pre>// In MainActivity<br>override fun onDestroy() {<br>    super.onDestroy()<br>    // This looks like the solution!<br>    (application as MainApplication).clearViewModel(&quot;MainActivity&quot;)<br>}</pre><p>But wait! This brings us back to square one.</p><h3>The Configuration Change Trap</h3><p>When a config change happens (e.g., rotation), onDestroy() is called! If we clear the ViewModel here, we lose the persistent data, defeating the whole purpose.</p><p>We need a way to distinguish between two types of destruction:</p><ul><li><strong>Permanent Destruction</strong> (e.g., the user presses back, or we call finish()): We <strong>must</strong> clear the ViewModel.</li><li><strong>Temporary Destruction</strong> (e.g., configuration change): We <strong>must not</strong> clear the ViewModel.</li></ul><h3>The Solution: isChangingConfigurations</h3><p>Luckily, Android gives us an API for exactly this: <strong>isChangingConfigurations()</strong>. This method returns true only if onDestroy() is being called as part of a temporary configuration change.</p><p>By adding a conditional check, we ensure our ViewModel is only cleared when the Activity is permanently going away:</p><pre>// In MainActivity<br>override fun onDestroy() {<br>    super.onDestroy()<br>// Only clear the ViewModel if this is NOT a configuration change.<br>    if (!isChangingConfigurations) {<br>        (application as MainApplication).clearViewModel(&quot;MainActivity&quot;)<br>    }<br>}</pre><p><strong>TADA!</strong> We have successfully built a system that mimics how ViewModel persistence works:</p><ul><li>It stores the state in a place with a <strong>longer lifecycle</strong> (MainApplication).</li><li>It uses a conditional check (isChangingConfigurations) to know when to <strong>persist</strong> or <strong>dispose</strong> of the state.</li></ul><h3>The Real Implementation: ViewModelStore</h3><p>This entire DIY implementation perfectly mirrors the internal logic of the Android Framework!</p><p>If you were to peek under the hood of ComponentActivity (which AppCompatActivity extends), you would find that it holds an instance of <strong>ViewModelStore</strong>.</p><p>During a configuration change, the Android system saves a special object called <strong>NonConfigurationInstances</strong> just before the Activity is destroyed.</p><pre>static final class NonConfigurationInstances {<br>    Object custom;<br>    ViewModelStore viewModelStore;<br>}</pre><p>This ViewModelStore is essentially what our HashMap&lt;String, MainViewModel&gt; was!</p><p>The <strong>ViewModelStore</strong> is then retrieved by the new Activity instance in its onCreate() method and used to supply the persistent ViewModel.</p><h3>Lifecycle Ownership</h3><p>But wait, where is the ViewModelStore itself kept?</p><p>Just as we used the long-lived <strong>Application</strong> class, the Android framework uses a component called the <strong>ActivityThread</strong>—a process-level component whose lifecycle is tied to the <strong>Application process</strong>. The ActivityThread is what internally holds onto the NonConfigurationInstances (and thus the ViewModelStore) during the brief period the Activity is being destroyed and recreated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RGipmfEDfvNQQp_TSIEHww.png" /><figcaption>ViewModel internal classes flow</figcaption></figure><p>This is why ViewModels work not just for Activities, but also for <strong>Fragments</strong> and <strong>Compose Composables</strong>—the framework simply ensures that the ViewModelStore is held by a <strong>Lifecycle Owner</strong> (or component) whose life is greater than the component using the ViewModel.</p><p>Now you know the secret! It’s all about finding a long-lived home and knowing when to clean up. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e690afbf28be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Higher-Order Functions in Kotlin Explained (So Anyone Can Understand!]]></title>
            <link>https://medium.com/@jayashree.sudalagunta/higher-order-functions-in-kotlin-explained-so-anyone-can-understand-f9d1c293ea43?source=rss-d949e0a7c2c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9d1c293ea43</guid>
            <category><![CDATA[kotlin-hof]]></category>
            <category><![CDATA[higher-order-function]]></category>
            <category><![CDATA[kotlin-beginners]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Jayashree Sudalagunta]]></dc:creator>
            <pubDate>Mon, 29 Sep 2025 05:23:23 GMT</pubDate>
            <atom:updated>2025-09-29T05:23:23.072Z</atom:updated>
            <content:encoded><![CDATA[<p>When you first hear <em>“higher-order function”</em>, it sounds like something only hardcore programmers would care about.<br> But the truth is: higher-order functions are simple, powerful, and you’ve probably been using the same idea in daily life without even realizing it.</p><p>Let’s break it down step by step.</p><p><strong>First, what is a Function?</strong></p><p>A <strong>function</strong> is just a small reusable action.</p><p>Think of your <strong>TV</strong>.</p><ul><li>It already knows how to <strong>change channels</strong>, <strong>increase volume</strong>, or <strong>mute the sound</strong>.</li><li>You don’t manually open the TV and change wires each time.</li><li>Instead, you press a button on the remote.</li></ul><p>In programming, a <strong>function</strong> works the same way.</p><ul><li>It’s a small piece of code that performs a task.</li><li>You “call” it, and it does the work.</li></ul><p>Example:</p><pre>fun turnOn() {<br> println(“TV is ON”)<br>}</pre><p>Here, turnOn() is like pressing the power button.</p><p><strong>What is a Higher-Order Function?</strong></p><p>When you search with what is higher order function in google you will get below explanation everywhere</p><p>A <strong>higher-order function (HOF)</strong> is a function that:</p><ol><li>Can <strong>take another function as input.</strong></li><li>Or <strong>return a function as output</strong>.</li></ol><p>I know you might have already read about above 2 points but still you are not sure how and why we need this, so lets take same analogy of TV and try to understand.</p><p>Now, imagine your TV remote.</p><ul><li>The <strong>TV</strong> already knows the actions.</li><li>But <strong>you decide which button to press</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Z-imRk9EpdSRrbc5d_yVg.png" /><figcaption>Normal functions versus HOF</figcaption></figure><p>A <strong>higher-order function (HOF)</strong> works the same way:</p><ul><li>It can <strong>take another function as input</strong> (like pressing a button to decide what action to run).</li><li>Or it can <strong>return a function as output</strong> (like the remote giving you a special “shortcut button” for later).</li></ul><p>So instead of just handling data, higher-order functions handle <strong>instructions</strong>.</p><p><strong>Part 1: Function Taking a Function</strong></p><p><strong>Example:</strong></p><p>Without Higher-Order Functions</p><pre><br>fun pressVolumeUp() {<br> println(“Volume Up”)<br>}</pre><pre>fun pressChannelDown() {<br> println(“Channel Down”)<br>}</pre><p>Here, we need different functions for each action. If the remote had 50 buttons, we’d have 50 separate functions. Too repetitive!</p><p>With a Higher-Order Function</p><pre>fun pressButton(action: () -&gt; Unit) {<br> action()<br>}</pre><pre>fun main() {<br> pressButton { println(“Volume Up”) }<br> pressButton { println(“Channel Down”) }<br>}</pre><p>Here’s what’s happening:</p><ul><li>pressButton is a <strong>higher-order function</strong>.</li><li>It doesn’t care <em>which button</em> you press.</li><li>It just executes the action (function) you pass to it.</li></ul><p>What is action: () -&gt; Unit?</p><p>This is the <strong>little note you hand to the remote</strong>.<br> It says: <em>“When I press this button, here’s what should happen.”</em></p><ul><li>The part () means → the instruction doesn’t need any input.</li><li>The part -&gt; Unit means → the instruction doesn’t give anything back.</li></ul><p>So, action: () -&gt; Unit simply means: <em>“I will take an instruction that does something, but doesn’t need input or give an answer back.”</em></p><p>✅ One reusable function for all remote actions.</p><p><strong>Part 2: Function Returning a Function</strong></p><p>So far, we saw higher-order functions that <strong>accept a function as input</strong> (like pressing a remote button with an instruction).<br> But sometimes, a function can also <strong>give you back another function</strong> to use later.</p><p>Imagine you buy a <strong>programmable remote</strong>.</p><ul><li>Instead of only using the built-in buttons, you can ask the remote to <strong>create a new button</strong> for you.</li><li>For example: “In remote, we can have a button that always sets the TV to Netflixl.”</li><li>The remote gives you this new button — and you can use it whenever you want.</li></ul><p>In Kotlin, this is done by having a function that <strong>returns another function</strong>.</p><p>Kotlin Example</p><pre>// This higher-order function RETURNS another function<br>fun createGreeting(message: String): (String) -&gt; String {<br> return { name -&gt; “$message, $name” }<br>}</pre><pre>fun main() {<br> val morningGreeting = createGreeting(“Good Morning”)<br> val eveningGreeting = createGreeting(“Good Evening”)</pre><pre>println(morningGreeting(“Alice”)) // Good Morning, Alice<br> println(eveningGreeting(“Bob”)) // Good Evening, Bob<br>}</pre><h3>Where Do We Use Higher-Order Functions?</h3><p>You actually use this idea in programming every day (especially in Kotlin).</p><ol><li>Filtering a List</li></ol><pre>val numbers = listOf(1, 2, 3, 4, 5)<br>val evens = numbers.filter { it % 2 == 0 }<br>println(evens) // [2, 4]</pre><p>👉 .filter is a higher-order function. You decide the rule (keep even numbers).</p><p>2. Sorting Data</p><pre>val names = listOf(“Charlie”, “Alice”, “Bob”)<br>val sorted = names.sortedBy { it.length }<br>println(sorted) // [Bob, Alice, Charlie]</pre><p>👉 .sortedBy is a higher-order function. You tell it how to sort (by length).</p><p>3. Button Clicks in Android</p><pre>button.setOnClickListener {<br> println(“Button clicked!”)<br>}</pre><p>👉 The button already knows how to detect clicks. You decide what happens when it’s clicked.</p><h3>Why Are They Powerful?</h3><ul><li><strong>Less repetition</strong> → one function works for many actions.</li><li><strong>More flexibility</strong> → you can change behavior anytime.</li><li><strong>Cleaner code</strong> → shorter, easier to read, and maintain.</li></ul><p>Think of them as a <strong>universal remote</strong>: one device, endless possibilities depending on the button you press.</p><h3>🎉 Final Takeaway</h3><p>A higher-order function is simply:<br> 👉 <em>“A function that can work with other functions.”</em></p><p>They make your programs flexible, reusable, and easy to customize — just like a TV remote lets you control your TV without needing 50 different devices.</p><p>So next time you filter a list, sort data, or handle a button click in Kotlin, remember: you’re already pressing the “buttons” of higher-order functions!</p><p>✨ That’s it — higher-order functions explained in the simplest way possible using a TV remote analogy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9d1c293ea43" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>