<?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 G M MUFEED on Medium]]></title>
        <description><![CDATA[Stories by G M MUFEED on Medium]]></description>
        <link>https://medium.com/@gangolimufeed?source=rss-66e1d0485569------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Y4w_IegQoP3wsigSLW0Z5w.jpeg</url>
            <title>Stories by G M MUFEED on Medium</title>
            <link>https://medium.com/@gangolimufeed?source=rss-66e1d0485569------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 11:10:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gangolimufeed/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[Executors vs Coroutines in Android ML & CameraX: Understanding Threading for Real-Time Vision]]></title>
            <link>https://medium.com/@gangolimufeed/executors-vs-coroutines-in-android-ml-camerax-understanding-threading-for-real-time-vision-0122dff294ef?source=rss-66e1d0485569------2</link>
            <guid isPermaLink="false">https://medium.com/p/0122dff294ef</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[camerax]]></category>
            <category><![CDATA[tflite]]></category>
            <dc:creator><![CDATA[G M MUFEED]]></dc:creator>
            <pubDate>Sun, 10 Aug 2025 05:19:09 GMT</pubDate>
            <atom:updated>2025-08-10T05:22:03.622Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Why CameraX requires Executors, how ML models need thread safety, and bridging the gap with asCoroutineDispatcher</em></p><p>Modern Android apps increasingly use <strong>on-device Machine Learning (ML)</strong> and <strong>real-time camera input</strong> to power features like face detection, object tracking, and OCR. Thanks to libraries like <strong>CameraX</strong>, <strong>TensorFlow Lite</strong>, and <strong>ML Kit</strong>, it’s easier than ever to implement — but behind the scenes, performance and responsiveness depend heavily on <strong>how you manage threads and concurrency</strong>.</p><h3>Understanding Executors: The Thread Managers</h3><p>An Executor in Java (and Android) is a class that manages a pool of threads. Instead of creating and managing threads manually, you submit tasks to an Executor, and it handles the execution.</p><h4><strong>Types of Executors</strong></h4><p><strong>Single Thread Executor:</strong></p><pre>// All tasks run on one background thread, one after another<br>val executor = Executors.newSingleThreadExecutor()</pre><p><strong>Fixed Thread Pool:</strong></p><pre>// Uses exactly 4 threads, tasks distributed among them<br>val executor = Executors.newFixedThreadPool(4)</pre><p><strong>Cached Thread Pool:</strong></p><pre>// Creates threads as needed, reuses idle threads<br>// Dynamically grows/shrinks based on demand<br>val executor = Executors.newCachedThreadPool()</pre><h3>Why Executors Matter for ML</h3><p>Machine Learning models (TensorFlow Lite, ONNX, ML Kit) are typically <strong>not thread-safe</strong>. But what does this actually mean?</p><p>When you load an ML model, it creates <strong>internal state and buffers</strong> in memory:</p><pre>// When you load a model, this happens internally:<br>class TensorFlowLiteModel {<br>    private var inputBuffer: FloatArray = FloatArray(224 * 224 * 3) // Input buffer<br>    private var outputBuffer: FloatArray = FloatArray(1000)         // Output buffer  <br>    private var interpreterState: InterpreterContext = ...          // Model weights, etc.<br>    <br>    fun run(input: Bitmap) {<br>        // Step 1: Write input data to inputBuffer<br>        preprocessImage(input, inputBuffer) // Modifies inputBuffer<br>        <br>        // Step 2: Run inference using the buffers<br>        interpreter.run(inputBuffer, outputBuffer) // Uses both buffers<br>        <br>        // Step 3: Read results from outputBuffer<br>        return parseResults(outputBuffer) // Reads outputBuffer<br>    }<br>}</pre><p><strong>The Problem with Multiple Threads:</strong></p><pre>val model = loadTensorFlowLiteModel() // One model instance with shared buffers<br><br>// ❌ DANGEROUS - Multiple threads accessing same model<br>val multiThreadExecutor = Executors.newFixedThreadPool(4)<br>multiThreadExecutor.execute { <br>    model.run(image1) // Thread 1: Writing to shared inputBuffer<br>}<br>multiThreadExecutor.execute { <br>    model.run(image2) // Thread 2: Also writing to same inputBuffer - COLLISION!<br>}</pre><p><strong>What Actually Happens:</strong></p><ol><li><strong>Thread 1</strong> starts processing image1, writes data to inputBuffer</li><li><strong>Thread 2</strong> starts processing image2, <strong>overwrites</strong> inputBuffer with different data</li><li><strong>Thread 1</strong> runs inference with corrupted buffer (mix of image1 and image2 data)</li><li><strong>Thread 2</strong> also runs inference with corrupted buffer</li><li><strong>Both get wrong results</strong> or the app crashes</li></ol><p>It’s like two people trying to write on the same piece of paper simultaneously — you get garbled text.</p><p><strong>Safe Sequential Execution:</strong></p><pre>val model = loadTensorFlowLiteModel() // Same model instance<br><br>// ✅ SAFE - Single thread ensures sequential access<br>val singleThreadExecutor = Executors.newSingleThreadExecutor()<br>singleThreadExecutor.execute { <br>    model.run(image1) // Completes fully: write→inference→read<br>}<br>singleThreadExecutor.execute { <br>    model.run(image2) // Starts AFTER image1 is done: write→inference→read  <br>}</pre><p><strong><em>Key Rule:</em></strong><em> ML models have </em><strong><em>shared internal state</em></strong><em> (buffers, weights, contexts) that gets corrupted when accessed from multiple threads simultaneously.</em></p><h3>The CameraX Executor Requirement</h3><p>Here’s the core challenge: CameraX’s ImageAnalysis <strong>requires</strong> an Executor, you cannot use coroutines directly.</p><pre>// ✅ This works - CameraX requires Executor<br>imageAnalysis.setAnalyzer(executor) { imageProxy -&gt;<br>    // Process camera frames<br>    analyzeImage(imageProxy)<br>}<br><br>// ❌ This doesn&#39;t exist - no direct coroutine support<br>imageAnalysis.setAnalyzer { imageProxy -&gt;<br>    launch { // This API doesn&#39;t exist<br>        analyzeImage(imageProxy)<br>    }<br>}</pre><h3>Why CameraX Requires Executors</h3><ol><li><strong>Java API Heritage</strong>: CameraX is built on Java and expects the Java Executor interface</li><li><strong>Threading Control</strong>: CameraX needs precise control over how camera frames are delivered</li><li><strong>Performance Guarantees</strong>: Camera operations require deterministic threading behavior</li><li><strong>Frame Delivery</strong>: Each frame must be processed in a controlled, predictable manner</li></ol><h3>The ML Threading Challenge: Why We Can’t Just Use Coroutines</h3><p>Here’s the separate issue — <strong>you can’t use regular coroutines for ML models</strong> regardless of CameraX. This is a completely independent threading problem:</p><h3>Coroutines Don’t Guarantee Single Thread</h3><p>When you launch coroutines with Dispatchers.IO, they can run on <strong>different threads</strong>:</p><pre>val model = loadTensorFlowLiteModel()<br><br>// ❌ DANGEROUS - Even without CameraX<br>repeat(5) {<br>    lifecycleScope.launch(Dispatchers.IO) { <br>        println(&quot;Running on: ${Thread.currentThread().name}&quot;)<br>        model.run(input) // Each might be on different thread!<br>    }<br>}<br><br>// Output might be:<br>// Running on: DefaultDispatcher-worker-1<br>// Running on: DefaultDispatcher-worker-2  ← Different thread!<br>// Running on: DefaultDispatcher-worker-3  ← Different thread!<br>// Running on: DefaultDispatcher-worker-1  ← Back to first thread<br>// Running on: DefaultDispatcher-worker-2  ← Different thread again!</pre><p><strong>The Problem</strong>: Dispatchers.IO uses a <strong>thread pool</strong> with multiple worker threads. Your coroutines get distributed across these threads, which breaks ML model thread safety and can cause crashes.</p><h3>ML Models Need Thread Safety</h3><p>ML frameworks like TensorFlow Lite have internal state that gets corrupted when accessed from multiple threads:</p><pre>// ❌ THIS WILL CRASH - Multiple threads accessing model<br>lifecycleScope.launch(Dispatchers.IO) { <br>    model.run(input1) // Thread A modifying model state<br>}<br>lifecycleScope.launch(Dispatchers.IO) { <br>    model.run(input2) // Thread B also modifying model state - CORRUPTION!<br>}</pre><h3>Solutions: Forcing Single Thread Execution</h3><p>If you wanted to use coroutines for ML , you’d need to ensure single-thread execution:</p><p><strong>Option 1: Limited Parallelism</strong></p><pre>// Create dispatcher that uses only ONE thread<br>val singleThreadDispatcher = Dispatchers.IO.limitedParallelism(1)<br><br>lifecycleScope.launch(singleThreadDispatcher) {<br>    model.run(input1) // Always same thread<br>}<br>lifecycleScope.launch(singleThreadDispatcher) {<br>    model.run(input2) // Always same thread, runs after first<br>}</pre><p><strong>Option 2: Single Thread Dispatcher</strong></p><pre>@OptIn(ExperimentalCoroutinesApi::class)<br>val singleThreadDispatcher = newSingleThreadContext(&quot;ML-Thread&quot;)<br><br>lifecycleScope.launch(singleThreadDispatcher) {<br>    model.run(input1) // Guaranteed same thread<br>}</pre><p><strong>Option 3: Convert Executor to Dispatcher</strong></p><pre>val executor = Executors.newSingleThreadExecutor()<br>val dispatcher = executor.asCoroutineDispatcher()<br><br>lifecycleScope.launch(dispatcher) {<br>    model.run(input1) // Uses executor&#39;s single thread<br>}</pre><h3>Why We Use the Executor + asCoroutineDispatcher() Pattern</h3><p><strong>Two separate problems:</strong></p><ol><li><strong>CameraX API</strong>: Requires Executor (Java legacy)</li><li><strong>ML Thread Safety</strong>: Requires single thread execution (model limitation)</li></ol><p><strong>One elegant solution:</strong> Use Executor for CameraX, convert to Dispatcher for coroutines, both share the same underlying thread.</p><p>Now you can see why this pattern is so effective, it solves <strong>both problems simultaneously</strong>:</p><pre>// We need executor anyway for CameraX<br>val executor = Executors.newSingleThreadExecutor() <br><br>// Convert it for coroutines - reuses the same thread<br>val dispatcher = executor.asCoroutineDispatcher()<br><br>// Problem 1: CameraX requirement ✅<br>imageAnalysis.setAnalyzer(executor) { imageProxy -&gt;<br>    // Already on single thread<br>    <br>    // Problem 2: ML thread safety ✅<br>    CoroutineScope(dispatcher).launch {<br>        // Uses SAME thread as executor<br>        // So ML model is safe<br>        model.run(imageProxy)<br>    }<br>}</pre><h3>Alternative: Separate Threads for Camera and ML</h3><p>It’s worth noting that <strong>CameraX and ML don’t have to run on the same thread</strong>. You could use separate threads:</p><pre>// Option 1: Separate threads<br>val cameraExecutor = Executors.newSingleThreadExecutor()    // For CameraX<br>val mlExecutor = Executors.newSingleThreadExecutor()        // For ML inference<br>val mlDispatcher = mlExecutor.asCoroutineDispatcher()<br><br>imageAnalysis.setAnalyzer(cameraExecutor) { imageProxy -&gt;<br>    // Running on camera thread<br>    <br>    CoroutineScope(mlDispatcher).launch {<br>        // This switches to ML thread<br>        model.run(imageProxy)<br>    }<br>}</pre><p><strong>Why share the thread?</strong></p><ul><li><strong>Less overhead</strong>: No thread switching between camera processing and ML inference</li><li><strong>Simpler resource management</strong>: Only one executor to manage and shutdown</li><li><strong>Better performance</strong>: Eliminates the cost of passing data between threads</li></ul><h3>Practical Implementation Pattern</h3><p><strong>Step 1: Set Up Threading Infrastructure</strong></p><pre>class CameraMLProcessor {<br>    // Single thread executor - required by CameraX and safe for ML<br>    private val executor = Executors.newSingleThreadExecutor()<br>    <br>    // Convert to coroutine dispatcher - enables coroutines on same thread<br>    private val inferenceDispatcher = executor.asCoroutineDispatcher()<br>    <br>    // Your ML model<br>    private lateinit var model: YourMLModel<br>    <br>    fun cleanup() {<br>        model.close()<br>        executor.shutdown()<br>    }<br>}</pre><p><strong>Step 2: CameraX Integration</strong></p><pre>fun setupCamera() {<br>    val imageAnalysis = ImageAnalysis.Builder().build()<br>    <br>    // CameraX requires Executor - provide it<br>    imageAnalysis.setAnalyzer(executor) { imageProxy -&gt;<br>        processFrame(imageProxy)<br>    }<br>    <br>    cameraProvider.bindToLifecycle(this, cameraSelector, imageAnalysis)<br>}</pre><p><strong>Step 3: Hybrid Processing — Executor + Coroutines</strong></p><pre>private fun processFrame(imageProxy: ImageProxy) {<br>    // We&#39;re on the executor thread (required by CameraX)<br>    <br>    // Launch coroutine using the SAME thread via asCoroutineDispatcher<br>    CoroutineScope(inferenceDispatcher).launch {<br>        try {<br>            // ML inference happens on same thread as CameraX executor<br>            val results = runMLInference(imageProxy)<br>            <br>            // Switch to main thread for UI updates<br>            withContext(Dispatchers.Main) {<br>                displayResults(results)<br>            }<br>        } finally {<br>            // Always close to prevent memory leaks<br>            imageProxy.close()<br>        }<br>    }<br>}<br><br>private suspend fun runMLInference(imageProxy: ImageProxy): List&lt;Result&gt; = <br>    withContext(inferenceDispatcher) {<br>        // This runs on the same thread as the executor<br>        // Thread-safe for ML model usage<br>        model.process(imageProxy)<br>    }</pre><h3>Understanding the Threading Flow</h3><p>Let’s trace what happens:</p><ol><li><strong>Camera Frame Arrives</strong>: CameraX calls your analyzer on the executor thread</li><li><strong>Coroutine Launch</strong>: CoroutineScope(inferenceDispatcher).launch starts a coroutine</li><li><strong>Same Thread Execution</strong>: Since inferenceDispatcher = executor.asCoroutineDispatcher(), the coroutine runs on the same thread</li><li><strong>ML Inference</strong>: Model processes the frame safely (single thread)</li><li><strong>Context Switch</strong>: withContext(Dispatchers.Main) moves to UI thread</li><li><strong>UI Update</strong>: Display results on main thread</li><li><strong>Cleanup</strong>: imageProxy.close() prevents memory leaks</li></ol><h3>Summary: The Threading Strategy</h3><p>For CameraX + ML applications, follow this pattern:</p><ol><li><strong>Create Single-Thread Executor</strong>: Executors.newSingleThreadExecutor() for ML thread safety</li><li><strong>Convert to Dispatcher</strong>: executor.asCoroutineDispatcher() for coroutine compatibility</li><li><strong>Use Executor for CameraX</strong>: Required by the setAnalyzer() API</li><li><strong>Use Dispatcher for Coroutines</strong>: Clean async patterns inside the analyzer</li><li><strong>Ensure Proper Cleanup</strong>: Close models and shutdown executors</li></ol><p>The key insight: <strong>You don’t choose between Executors and Coroutines. You use both where they’re most effective.</strong> Executors for API requirements and thread control, Coroutines for clean async code, and asCoroutineDispatcher() as the bridge between them.</p><p><em>Understanding this threading pattern is crucial for building responsive, crash-free real-time ML applications on Android.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0122dff294ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding CameraX Image Analysis Strategies: A Deep Dive into Buffer Management]]></title>
            <link>https://medium.com/@gangolimufeed/understanding-camerax-image-analysis-strategies-a-deep-dive-into-buffer-management-48ccdae8cc38?source=rss-66e1d0485569------2</link>
            <guid isPermaLink="false">https://medium.com/p/48ccdae8cc38</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[android-camera]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[G M MUFEED]]></dc:creator>
            <pubDate>Fri, 08 Aug 2025 19:24:28 GMT</pubDate>
            <atom:updated>2025-08-08T19:24:28.156Z</atom:updated>
            <content:encoded><![CDATA[<p>When you use ImageAnalysis in CameraX, you’ve likely come across two strategies: STRATEGY_BLOCK_PRODUCER and STRATEGY_KEEP_ONLY_LATEST. Let’s understand how they work and how they affect frame drops, memory usage, and performance.</p><p><strong>Picture this scenario</strong>:</p><ul><li>Your camera is capturing frames at <strong>30 FPS</strong>.</li><li>Your ML model takes <strong>200ms</strong> to process each frame.</li><li>Simple math: you can only process <strong>5 frames per second</strong>.</li><li>That leaves <strong>25 extra frames per second</strong> unprocessed.</li></ul><p>This is where <strong>CameraX’s analysis strategies</strong> come into play.</p><h3>The Two Strategies:</h3><p><strong>1. </strong><strong>STRATEGY_KEEP_ONLY_LATEST </strong><br>This approach focuses on always providing the <strong>most recent frame</strong>, ensuring your analyzer stays in sync with the live camera feed.</p><pre>imageAnalysis.backpressureStrategy = ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST</pre><p><strong>The Flow:</strong></p><pre>Camera produces: Frame1 → Frame2 → Frame3 → Frame4 → Frame5<br>Analyzer busy with Frame1...<br><br>What happens:<br>- Frame2, Frame3, Frame4 get dropped automatically<br>- When Frame1 processing completes, Frame5 (latest) is delivered<br>- Result: Frame1 → Frame5 (frames 2,3,4 discarded)</pre><p><strong>Visual Representation:</strong></p><pre>Camera:   [F1] [F2] [F3] [F4] [F5] [F6] [F7]<br>           ↓    ×    ×    ×    ↓    ×    ×<br>Analyzer:  Process F1........  Process F5........</pre><p><strong>2. </strong><strong>STRATEGY_BLOCK_PRODUCER</strong></p><p>This appoach ensures no frame is lost by blocking the camera pipeline:</p><pre>imageAnalysis.backpressureStrategy = ImageAnalysis.STRATEGY_BLOCK_PRODUCER</pre><p><strong>The Flow:</strong></p><pre>Camera produces: Frame1 → Frame2 → Frame3 → Frame4 → Frame5<br>Analyzer busy with Frame1...<br><br>What happens:<br>- Camera STOPS producing Frame2, Frame3, Frame4 <br>- Camera waits until Frame1 processing completes<br>- Only then does camera capture Frame2<br>- Result: Frame1 → Frame2 (sequential, but with gaps)</pre><p><strong>Visual Representation:</strong></p><pre>Camera:   [F1] ──BLOCKED── ──BLOCKED── ──BLOCKED── [F2] ──BLOCKED── [F3]<br>           ↓                                      ↓                ↓<br>Analyzer:  Process F1............................ Process F2.... Process F3....</pre><blockquote><strong>You might be wondering <br></strong>1. Where does the next frame come from if the analyzer is still busy processing?</blockquote><blockquote>2. And if new frames keep arriving during STRATEGY_BLOCK_PRODUCER, won’t they end up using more memory?</blockquote><blockquote>To answer these two questions, it’s important to first understand how memory management works in CameraX during image analysis.</blockquote><p>When the camera captures an image, the raw pixel data doesn’t go into your app’s Java heap. Instead, it’s stored in <strong>native memory buffers</strong>:</p><pre>Camera Sensor → Native Memory Buffer (C/C++ allocated)<br>                     ↓<br>                Image object (Java wrapper)<br>                     ↓  <br>                ImageProxy (CameraX wrapper)<br>                     ↓<br>                Your Analyzer</pre><h3>Buffer Allocation:</h3><p>STRATEGY_KEEP_ONLY_LATEST with 3 buffers:</p><pre>Frame 1 arrives:<br><strong>[F1 data]</strong> [Available] [Available] <br>    ↓<br>Analyzer: Processing F1...<br><br>Frame 2 arrives :<br><strong>[F1 processing] [F2 data]</strong> [Available] <br><br>Frame 3 arrives:<br><strong>[F1 processing] [F3 data]</strong> [Available] <br>                     ↑<br>             F2 gets dropped, F3 takes its place (keep only latest)<br><br>Frame 4 arrives:<br><strong>[F1 processing] [F4 data]</strong> [Available] <br>                     ↑<br>             F3 gets dropped, F4 takes its place (keep only latest)<br><br>Frame 5 arrives:<br><strong>[F1 processing] [F5 data]</strong> [Available] <br>                     ↑<br>             F4 gets dropped, F5 takes its place (keep only latest)<br><br>F1 processing completes, next frame to process is the latest available:<br>[Available]<strong> [F5 data]</strong> [Available] [<br>                ↓<br>    Analyzer: Processing F5 (latest frame, F2,F3,F4 were dropped)</pre><p>STRATEGY_BLOCK_PRODUCER with 4 Buffers:</p><pre>Frame 1 arrives:<br><strong>[F1 data]</strong> [Available] [Available] [Available]<br>    ↓<br>Analyzer: Processing F1...<br><br>Frame 2 arrives :<br><strong>[F1 processing] [F2 data]</strong> [Available] [Available]<br><br>F1 processing completes:<br>Frame 3 arrives :<br><strong>[F1 processing] [F2 data]</strong> [F3 data] [Available]<br>                    ↓         <br>        Analyzer: Processing F2 next                      </pre><p><em>If the buffer size gets full, then we can also lose frames in the </em><em>STRATEGY_BLOCK_PRODUCER</em></p><pre>Frame 1 arrives:<br><strong>[F1 data]</strong> [Available] [Available]<br>    ↓<br>Analyzer: Processing F1...<br><br>Frame 2 arrives :<br><strong>[F1 processing] [F2 data]</strong> [Available]<br><br>Frame 3arrives :<br><strong>[F1 processing] [F2 data] [F3 data]</strong><br>                            ↑<br>                    Buffer pool is now FULL!<br><br>Frame 4 arrives :<br><strong>[F1 processing] [F3 data] [F4 data]</strong><br>                    ↑<br>            F2 gets overwritten with F4 (F2 lost due to buffer limit)<br><br>Frame 5 arrives :<br><strong>[F1 processing] [F4 data] [F5 data]</strong><br>                            ↑<br>                    F3 gets overwritten with F5 (F3 lost)<br><br>F1 processing completes:<br>[Available] <strong>[F4 data] [F5 data]</strong><br>                ↓         <br>        Analyzer: Processing F4 next (F2, F3 were lost due to buffer overflow)</pre><h3>Conclusion</h3><p>Understanding CameraX’s image analysis strategies and buffer management is crucial for building robust camera applications. The key takeaways are:</p><ol><li><strong>STRATEGY_KEEP_ONLY_LATEST</strong> is ideal for real-time applications where current data matters more than completeness</li><li><strong>STRATEGY_BLOCK_PRODUCER</strong> ensures no frames are lost but can cause memory pressure and latency</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48ccdae8cc38" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>