<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ concurrency - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ concurrency - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Fri, 22 May 2026 17:39:52 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/concurrency/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Concurrency vs. Parallelism: What’s the Difference and Why Should You Care? ]]>
                </title>
                <description>
                    <![CDATA[ In software engineering, certain concepts appear deceptively simple at first glance but fundamentally shape the way we design and architect systems. Concurrency and parallelism are two such concepts that warrant careful examination. These terms are f... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/concurrency-vs-parallelism-whats-the-difference-and-why-should-you-care/</link>
                <guid isPermaLink="false">68f25bf491a578e35f37419a</guid>
                
                    <category>
                        <![CDATA[ Computer Science ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ concurrency ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Parallel Programming ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Wisdom Usa ]]>
                </dc:creator>
                <pubDate>Fri, 17 Oct 2025 15:08:36 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1760622633358/ad43bbd8-116c-42eb-95b7-0ef70156983a.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In software engineering, certain concepts appear deceptively simple at first glance but fundamentally shape the way we design and architect systems. Concurrency and parallelism are two such concepts that warrant careful examination.</p>
<p>These terms are frequently used interchangeably, even among experienced developers. But while they may sound similar and occasionally overlap in practice, they address distinctly different problems and serve separate architectural goals. Understanding this distinction is not just an academic exercise. It directly impacts how you build scalable, efficient systems.</p>
<p>Whether you’re developing a high-traffic web server, training complex machine learning models, or optimising application performance, a solid grasp of these concepts can mean the difference between a solution that merely functions and one that scales elegantly under real-world conditions.</p>
<p>This article provides a comprehensive breakdown of both concepts through visual analogies, practical examples, and technical implementations. By the end, you will be equipped to confidently apply these principles in your software projects.</p>
<h3 id="heading-heres-what-well-cover">Here’s what we’ll cover:</h3>
<ol>
<li><p><a class="post-section-overview" href="#heading-understanding-the-fundamental-concepts">Understanding the Fundamental Concepts</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-the-kitchen-analogy">The Kitchen Analogy</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-what-concurrency-looks-like-in-practice">What Concurrency Looks Like in Practice</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-python-example-implementing-concurrency-with-asyncio">Python Example: Implementing Concurrency with asyncio</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-what-parallelism-looks-like-in-practice">What Parallelism Looks Like in Practice</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-python-example-implementing-parallelism-with-multiprocessing">Python Example: Implementing Parallelism with multiprocessing</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-concurrency-vs-parallelism-a-detailed-comparison">Concurrency vs. Parallelism: A Detailed Comparison</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-when-to-use-each">When to Use Each</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-real-world-applications-and-use-cases">Real-World Applications and Use Cases</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-concurrency-in-production-systems">Concurrency in Production Systems</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-parallelism-in-production-systems">Parallelism in Production Systems</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-hybrid-approaches">Hybrid Approaches</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-choosing-the-right-approach-for-your-problem">Choosing the Right Approach for Your Problem</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-common-pitfall-to-avoid">Common Pitfall to Avoid</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-why-this-distinction-matters-in-practice">Why This Distinction Matters in Practice</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-common-misconceptions-and-clarifications">Common Misconceptions and Clarifications</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-practical-implementation-strategies">Practical Implementation Strategies</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-when-implementing-concurrency">When Implementing Concurrency</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-when-implementing-parallelism">When Implementing Parallelism</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-tools-and-technologies-by-language">Tools and Technologies by Language</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-further-learning-resources">Further Learning Resources</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ol>
<h2 id="heading-understanding-the-fundamental-concepts">Understanding the Fundamental Concepts</h2>
<p>Before diving into implementations, let’s establish some clear definitions:</p>
<p><strong>Concurrency</strong> refers to the ability of a system to manage multiple tasks within overlapping time periods. It does not necessarily mean these tasks execute at the exact same instant. Rather, concurrency is about structuring a program to handle multiple operations by interleaving their execution, often on a single processor core.</p>
<p><strong>Parallelism</strong>, by contrast, involves the simultaneous execution of multiple tasks. This typically requires multiple CPU cores or processors working in tandem, with each handling a separate portion of the workload at the same time.</p>
<h3 id="heading-the-kitchen-analogy">The Kitchen Analogy</h3>
<p>Consider the process of cooking as a helpful mental model:</p>
<p>A concurrent kitchen employs a single chef who rapidly switches between preparing multiple dishes. The chef might chop vegetables for one dish, then stir a sauce for another, then return to the first dish to continue preparation. From an observer's perspective, it appears that multiple dishes are being prepared "at once," but in reality, the chef is performing one action at a time in rapid succession.</p>
<p>A parallel kitchen has multiple chefs, each working on different dishes simultaneously. One chef prepares the appetiser while another works on the main course, and a third handles dessert. True simultaneous work is happening across multiple workers.</p>
<p>Same kitchen, different strategies, different outcomes.</p>
<h2 id="heading-what-concurrency-looks-like-in-practice">What Concurrency Looks Like in Practice</h2>
<p><a target="_blank" href="https://mechdampiitb.github.io/cs751_shyamsundar/"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1760010754774/e4563560-b9b2-42e0-8c69-5c052db2656c.png" alt="Visual comparison between concurrency and parallelism in task execution. On the left, a single CPU alternates between Task 1 and Task 2 (or Thread 1 and Thread 2), illustrating concurrency without true parallelism. On the right, two CPUs execute Task 1 and Task 2 simultaneously, illustrating both concurrency and parallelism." class="image--center mx-auto" width="866" height="643" loading="lazy"></a></p>
<p>Concurrency is fundamentally about task scheduling, coordination, and resource management. It enables a program to handle multiple operations by strategically interleaving their execution, whether on a single core or across multiple threads.</p>
<p>A practical example: when you stream a video on YouTube while your device downloads a file in the background and your messaging app checks for new messages, your CPU is rapidly context-switching between these tasks. Each task gets a slice of processing time, creating the illusion of simultaneous execution even on a single-core processor.</p>
<h3 id="heading-python-example-implementing-concurrency-with-asyncio">Python Example: Implementing Concurrency with asyncio</h3>
<p>To examine concurrency in more detail, we’ll create a simple application which gets data on various APIs asynchronously. This is an example of how Python’s library, asyncio, lets us spawn multiple network operations without blocking so we can effectively use the waiting time.</p>
<p>In this implementation, we’ll be simulating API calls to a weather service, a news service, and a user profile database. Pay attention to the fact that all three requests begin nearly at the same time, yet the program doesn’t wait until one of them is completed before it begins the next one.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> asyncio

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">fetch_data_from_api</span>(<span class="hljs-params">api_name, delay</span>):</span>
    print(<span class="hljs-string">f"Starting request to <span class="hljs-subst">{api_name}</span>..."</span>)
    <span class="hljs-keyword">await</span> asyncio.sleep(delay)  <span class="hljs-comment"># Simulates network I/O wait</span>
    print(<span class="hljs-string">f"Received response from <span class="hljs-subst">{api_name}</span>"</span>)
    <span class="hljs-keyword">return</span> <span class="hljs-string">f"Data from <span class="hljs-subst">{api_name}</span>"</span>

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">fetch_user_profile</span>(<span class="hljs-params">user_id</span>):</span>
    print(<span class="hljs-string">f"Fetching profile for user <span class="hljs-subst">{user_id}</span>..."</span>)
    <span class="hljs-keyword">await</span> asyncio.sleep(<span class="hljs-number">1.5</span>)
    print(<span class="hljs-string">f"Profile loaded for user <span class="hljs-subst">{user_id}</span>"</span>)
    <span class="hljs-keyword">return</span> {<span class="hljs-string">"user_id"</span>: user_id, <span class="hljs-string">"name"</span>: <span class="hljs-string">"John Doe"</span>}

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    <span class="hljs-comment"># All tasks start and are managed concurrently</span>
    results = <span class="hljs-keyword">await</span> asyncio.gather(
        fetch_data_from_api(<span class="hljs-string">"Weather API"</span>, <span class="hljs-number">2</span>),
        fetch_data_from_api(<span class="hljs-string">"News API"</span>, <span class="hljs-number">1</span>),
        fetch_user_profile(<span class="hljs-number">12345</span>)
    )
    print(<span class="hljs-string">"\nAll operations completed!"</span>)
    print(<span class="hljs-string">"Results:"</span>, results)

asyncio.run(main())
</code></pre>
<p><strong>What happens during execution:</strong></p>
<ol>
<li><p>All three async functions are initiated at approximately the same time.</p>
</li>
<li><p>The event loop manages their execution, switching between tasks when one is waiting (during <code>await</code> statements).</p>
</li>
<li><p>While one task waits for simulated I/O, the event loop allows other tasks to make progress.</p>
</li>
<li><p>The task with the shortest delay completes first, even though all were started together.</p>
</li>
<li><p>No task blocks the others, resulting in efficient use of the single thread.</p>
</li>
</ol>
<p><strong>Key insight:</strong> Concurrency optimises responsiveness and resource utilisation. It doesn’t inherently make individual tasks complete faster. Instead, it allows multiple tasks to make progress during the same time period, particularly when those tasks involve waiting for external resources.</p>
<h2 id="heading-what-parallelism-looks-like-in-practice">What Parallelism Looks Like in Practice</h2>
<p><a target="_blank" href="https://www.researchgate.net/figure/Parallelism-mechanism-in-OpenMP-with-multiple-CPU-threads_fig3_311454812"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1760010925777/c85a1976-96da-4f74-abba-62d1d0489d60.png" alt="Diagram illustrating the execution timeline of a parallel region using OpenMP. It shows how threads are forked and joined, with timestamps at the fork (`t_f`) and join (`t_j`), individual thread creation (`t_{i,s}`) and completion (`t_{i,c}`), as well as allocated memory per CPU/thread." class="image--center mx-auto" width="850" height="460" loading="lazy"></a></p>
<p>Parallelism concerns itself with genuine simultaneous execution. This approach leverages multiple CPU cores or processors to divide work and execute portions concurrently in real time.</p>
<p>Parallelism shines when dealing with CPU-intensive operations such as mathematical computations, image processing, video rendering, or training deep learning models.</p>
<h3 id="heading-python-example-implementing-parallelism-with-multiprocessing">Python Example: Implementing Parallelism with multiprocessing</h3>
<p>To better understand parallel execution, we’re going to make a program that carries out intensive calculations in a set of cores of CPUs. The given example relies on Python and the multiprocessing module to create different processes that are executed on different processor cores.</p>
<p>To work with a sufficiently complex example, we’ll compute the sum of the squares of millions of numbers. In contrast to the concurrent code sample, where we were waiting to receive I/O, we are actually doing some CPU-intensive work. You’ll notice the reduction in the time taken to execute the work when it’s shared by a number of cores.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> multiprocessing <span class="hljs-keyword">import</span> Process, current_process
<span class="hljs-keyword">import</span> time

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">compute_heavy_task</span>(<span class="hljs-params">task_name, iterations</span>):</span>
    <span class="hljs-string">"""Simulates a CPU-intensive operation"""</span>
    process_name = current_process().name
    print(<span class="hljs-string">f"<span class="hljs-subst">{task_name}</span> started on <span class="hljs-subst">{process_name}</span>"</span>)

    <span class="hljs-comment"># Simulate CPU-bound work</span>
    result = <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(iterations):
        result += i ** <span class="hljs-number">2</span>

    time.sleep(<span class="hljs-number">1</span>)  <span class="hljs-comment"># Additional simulated work</span>
    print(<span class="hljs-string">f"<span class="hljs-subst">{task_name}</span> completed on <span class="hljs-subst">{process_name}</span>. Result: <span class="hljs-subst">{result}</span>"</span>)
    <span class="hljs-keyword">return</span> result

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    start_time = time.time()

    <span class="hljs-comment"># Create separate processes for each task</span>
    p1 = Process(target=compute_heavy_task, args=(<span class="hljs-string">"Task 1"</span>, <span class="hljs-number">10000000</span>))
    p2 = Process(target=compute_heavy_task, args=(<span class="hljs-string">"Task 2"</span>, <span class="hljs-number">10000000</span>))
    p3 = Process(target=compute_heavy_task, args=(<span class="hljs-string">"Task 3"</span>, <span class="hljs-number">10000000</span>))

    <span class="hljs-comment"># Start all processes (they run on separate CPU cores)</span>
    p1.start()
    p2.start()
    p3.start()

    <span class="hljs-comment"># Wait for all processes to complete</span>
    p1.join()
    p2.join()
    p3.join()

    end_time = time.time()
    print(<span class="hljs-string">f"\nAll tasks completed in <span class="hljs-subst">{end_time - start_time:<span class="hljs-number">.2</span>f}</span> seconds"</span>)
</code></pre>
<p><strong>What happens during execution:</strong></p>
<ol>
<li><p>Three separate processes are spawned, each allocated to available CPU cores.</p>
</li>
<li><p>Each process runs independently with its own memory space and Python interpreter.</p>
</li>
<li><p>All three CPU-intensive calculations execute truly simultaneously across multiple cores.</p>
</li>
<li><p>The total runtime is determined by the longest-running task, not the cumulative sum of all tasks.</p>
</li>
<li><p>On a multi-core system, this completes approximately three times faster than sequential execution.</p>
</li>
</ol>
<p><strong>Key insight:</strong> Parallelism achieves actual speedup by distributing computational workload across multiple processors. This directly reduces total execution time for CPU-bound operations.</p>
<h2 id="heading-concurrency-vs-parallelism-a-detailed-comparison">Concurrency vs. Parallelism: A Detailed Comparison</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Aspect</td><td>Concurrency</td><td>Parallelism</td></tr>
</thead>
<tbody>
<tr>
<td><strong>Core Definition</strong></td><td>Managing and coordinating multiple tasks within overlapping time periods</td><td>Executing multiple tasks simultaneously across multiple processors</td></tr>
<tr>
<td><strong>Primary Goal</strong></td><td>Improve structure, responsiveness, and resource efficiency</td><td>Increase raw computational throughput and speed</td></tr>
<tr>
<td><strong>CPU Utilization</strong></td><td>Can work on single or multiple cores through interleaving</td><td>Requires multiple cores or processors for true parallelism</td></tr>
<tr>
<td><strong>Execution Model</strong></td><td>Task switching and scheduling</td><td>Simultaneous execution across hardware</td></tr>
<tr>
<td><strong>Optimal Use Case</strong></td><td>I/O-bound operations (network requests, file operations, database queries)</td><td>CPU-bound operations (mathematical computations, data processing, rendering)</td></tr>
<tr>
<td><strong>Common Implementation Techniques</strong></td><td>Async/await patterns, threads, coroutines, event loops</td><td>Multiprocessing, GPU computing, and distributed computing frameworks</td></tr>
<tr>
<td><strong>Performance Characteristic</strong></td><td>Reduces idle time and improves throughput without necessarily speeding up individual tasks</td><td>Directly reduces execution time by dividing the work</td></tr>
<tr>
<td><strong>Typical Applications</strong></td><td>Web servers, REST APIs, GUI applications, chat systems, and real-time notifications</td><td>Video encoding, scientific simulations, machine learning training, big data analytics</td></tr>
<tr>
<td><strong>Resource Overhead</strong></td><td>Lower (shared memory, lightweight context switching)</td><td>Higher (separate memory spaces, inter-process communication costs)</td></tr>
</tbody>
</table>
</div><h3 id="heading-when-to-use-each">When to Use Each:</h3>
<p>Use <strong>concurrency</strong> when you want to handle more tasks effectively within the same time period, particularly when those tasks spend time waiting for external resources.</p>
<p>Use <strong>parallelism</strong> when you want to complete tasks faster by leveraging multiple processors to divide the computational workload.</p>
<h2 id="heading-real-world-applications-and-use-cases">Real-World Applications and Use Cases</h2>
<h3 id="heading-concurrency-in-production-systems">Concurrency in Production Systems</h3>
<h4 id="heading-1-web-servers-and-apis">1. Web Servers and APIs</h4>
<p>Modern web frameworks like Node.js, Django with async views, and FastAPI handle thousands of simultaneous client connections. Each request may involve database queries, external API calls, or file operations. Concurrency allows the server to handle new requests while waiting for I/O operations from previous requests to complete.</p>
<h4 id="heading-2-real-time-communication">2. Real-Time Communication</h4>
<p>Chat applications, collaborative editing tools, and live streaming platforms manage multiple simultaneous connections. Messages must be received, processed, and broadcast to multiple clients concurrently without blocking any single connection.</p>
<h4 id="heading-3-mobile-applications">3. Mobile Applications</h4>
<p>Mobile apps perform background synchronization, push notification handling, and data caching while maintaining a responsive user interface. The UI thread remains free while background operations proceed concurrently.</p>
<h4 id="heading-4-microservices-orchestration">4. Microservices Orchestration</h4>
<p>Service meshes coordinate multiple API calls to different microservices, aggregating results efficiently without waiting for each call to complete sequentially.</p>
<h3 id="heading-parallelism-in-production-systems">Parallelism in Production Systems</h3>
<h4 id="heading-1-machine-learning-and-ai">1. Machine Learning and AI</h4>
<p>Training neural networks involves massive matrix computations that can be distributed across multiple GPU cores or even multiple machines. Frameworks like TensorFlow and PyTorch automatically parallelise operations across available hardware.</p>
<h4 id="heading-2-big-data-processing">2. Big Data Processing</h4>
<p>Distributed computing frameworks such as Apache Spark, Hadoop, and Dask divide large datasets across cluster nodes. Each node processes its portion of the data in parallel, enabling analysis of petabyte-scale datasets.</p>
<h4 id="heading-3-media-processing">3. Media Processing</h4>
<p>Video transcoding, image batch processing, and audio rendering leverage multiple CPU cores or GPUs. Each frame or segment can be processed independently in parallel.</p>
<h4 id="heading-4-scientific-computing">4. Scientific Computing</h4>
<p>Computational physics simulations, genome sequencing, and climate modelling require enormous computational resources. Parallelism across supercomputer clusters enables these calculations to complete in reasonable time frames.</p>
<h4 id="heading-5-financial-modelling">5. Financial Modelling</h4>
<p>Risk analysis and portfolio optimisation involve running thousands of scenarios. Parallel processing allows these computations to execute simultaneously, providing results quickly enough for real-time decision making.</p>
<h3 id="heading-hybrid-approaches">Hybrid Approaches</h3>
<p>In practice, sophisticated systems frequently combine both paradigms. Consider a modern web application:</p>
<ol>
<li><p>The web server handles client requests concurrently (handling multiple users simultaneously).</p>
</li>
<li><p>Each request may trigger parallel data processing tasks (such as image resizing across multiple cores).</p>
</li>
<li><p>The database connection pool manages concurrent query execution.</p>
</li>
<li><p>Background job workers process tasks in parallel (such as sending emails or generating reports).</p>
</li>
</ol>
<p>This layered approach leverages the strengths of both concurrency and parallelism to create systems that are both responsive and computationally efficient.</p>
<h2 id="heading-choosing-the-right-approach-for-your-problem">Choosing the Right Approach for Your Problem</h2>
<p>Understanding which paradigm to apply requires analysing the nature of your workload:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>If Your Task Is...</td><td>Choose...</td><td>Reasoning</td></tr>
</thead>
<tbody>
<tr>
<td><strong>I/O-bound</strong> (waiting for network, disk, or database operations)</td><td><strong>Concurrency</strong></td><td>Maximises efficiency by allowing other work to proceed during wait times. The bottleneck is not CPU computation but external resource availability.</td></tr>
<tr>
<td><strong>CPU-bound</strong> (heavy mathematical computation, data processing, rendering)</td><td><strong>Parallelism</strong></td><td>Distributes computational load across multiple processors, directly reducing execution time. The bottleneck is CPU capacity.</td></tr>
<tr>
<td><strong>Mixed workload</strong> (both I/O operations and intensive computation)</td><td><strong>Concurrency + Parallelism</strong></td><td>Concurrent handling of I/O operations combined with parallel processing of CPU-intensive segments provides optimal performance.</td></tr>
<tr>
<td><strong>Many small, independent tasks</strong></td><td><strong>Concurrency</strong> (if I/O) or <strong>Parallelism</strong> (if CPU)</td><td>Choose based on whether tasks are waiting or computing.</td></tr>
<tr>
<td><strong>Few large, divisible computations</strong></td><td><strong>Parallelism</strong></td><td>Split each computation across cores for maximum speedup.</td></tr>
</tbody>
</table>
</div><h3 id="heading-common-pitfall-to-avoid">Common Pitfall to Avoid</h3>
<p>A frequent mistake is attempting to use threading for CPU-bound tasks in languages with a Global Interpreter Lock (like Python's CPython) and expecting parallel speedups. In such cases, threads provide concurrency but not true parallelism.</p>
<p>The GIL ensures only one thread executes Python bytecode at a time, leading to context-switching overhead without genuine parallel execution. For CPU-bound work in Python, multiprocessing or C extensions are necessary for true parallelism.</p>
<h2 id="heading-why-this-distinction-matters-in-practice">Why This Distinction Matters in Practice</h2>
<p>Grasping the difference between concurrency and parallelism extends beyond writing faster code. It fundamentally influences how you architect systems and make technological decisions:</p>
<p>First of all, choosing the appropriate execution model for each component of your system leads to cleaner, more maintainable code. You avoid over-engineering solutions or applying the wrong tool to a problem.</p>
<p>Understanding these concepts also prevents wasteful patterns such as spawning unnecessary processes for I/O-bound work or using single-threaded approaches for parallelizable computations. This directly translates to reduced infrastructure costs.</p>
<p>Systems designed with proper concurrency models also scale horizontally more effectively. Those leveraging parallelism appropriately utilise hardware resources fully as you scale vertically.</p>
<p>In addition, you’ll get some key performance optimisations by choosing the right approach. When profiling reveals bottlenecks, knowing whether to optimise for concurrency or parallelism guides your refactoring efforts in the right direction.</p>
<p>Beyond this, in cloud environments where you pay for compute resources, efficient use of concurrency and parallelism directly affects operational costs. An efficiently concurrent system might handle 10x the load on the same hardware compared to a poorly designed synchronous alternative.</p>
<p>And these concepts are fundamental to backend engineering, distributed systems, DevOps, machine learning engineering, and systems programming. They appear frequently in technical interviews and are essential for senior engineering roles.</p>
<h2 id="heading-common-misconceptions-and-clarifications">Common Misconceptions and Clarifications</h2>
<h3 id="heading-using-threads-automatically-gives-me-parallelism">"Using threads automatically gives me parallelism."</h3>
<p>In reality, threads enable concurrency but do not guarantee parallel execution. In systems with a Global Interpreter Lock (like CPython) or on single-core machines, threads run concurrently but not in parallel. True parallelism requires multiple CPU cores and mechanisms that avoid locking constraints.</p>
<h3 id="heading-parallelism-is-always-faster-than-sequential-execution">"Parallelism is always faster than sequential execution."</h3>
<p>In fact, parallelism introduces overhead, including process creation, inter-process communication, and data synchronisation costs. For small tasks or I/O-bound operations, this overhead can outweigh benefits. Parallelism shows gains when the computational work justifies the overhead.</p>
<h3 id="heading-concurrency-and-parallelism-are-mutually-exclusive">"Concurrency and parallelism are mutually exclusive."</h3>
<p>As you’ve learned, modern high-performance systems routinely combine both. A web server can handle requests concurrently, with each request triggering parallel processing. Understanding how to layer these approaches is key to building sophisticated systems.</p>
<h3 id="heading-more-threads-or-processes-always-mean-better-performance">"More threads or processes always mean better performance."</h3>
<p>Beyond a certain point, adding more threads or processes leads to diminishing returns and even performance degradation due to increased context switching and resource contention. The optimal number depends on workload characteristics and available hardware.</p>
<h3 id="heading-asyncawait-makes-my-code-run-faster">“Async/await makes my code run faster."</h3>
<p>Async/await improves efficiency for I/O-bound operations by reducing idle time, but it does not speed up CPU-bound computations. It changes how waiting is handled, not how quickly individual operations execute.</p>
<h2 id="heading-practical-implementation-strategies">Practical Implementation Strategies</h2>
<h3 id="heading-how-to-implement-concurrency">How to Implement Concurrency</h3>
<p>To introduce concurrency into your programs, first you’ll need to find where time is wasted. Blocking operations that are held waiting on external resources are the best candidates to be put under concurrent execution.</p>
<p>Say you’re building a web scraper to fetch a bunch of data on a variety of sites. Every single HTTP request is most likely waiting until the server gets a response back. Other requests might be underway in your program instead of waiting around during this waiting period. These wait points are identifiable by profiling your application and searching the operations with network calls, file I/O, or database queries.</p>
<p>After you’ve discovered these wait points, the next big step will be to select the concurrency primitive. In Python, I/O-bound operations perform very well using the patterns of async/await with the support of the asyncio framework. It also comes with a minimal cost.</p>
<p>Take a situation when you have to retrieve user data in a REST API and query a database at the same time. With asyncio, you can write code that initiates both tasks almost simultaneously, and then have the event loop alternate between them during periods of waiting.</p>
<p>Here's a practical example:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> asyncio
<span class="hljs-keyword">import</span> aiohttp

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">fetch_user_api</span>(<span class="hljs-params">user_id</span>):</span>
    <span class="hljs-keyword">async</span> <span class="hljs-keyword">with</span> aiohttp.ClientSession() <span class="hljs-keyword">as</span> session:
        <span class="hljs-keyword">async</span> <span class="hljs-keyword">with</span> session.get(<span class="hljs-string">f'https://api.example.com/users/<span class="hljs-subst">{user_id}</span>'</span>) <span class="hljs-keyword">as</span> response:
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> response.json()

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">query_database</span>(<span class="hljs-params">user_id</span>):</span>
    <span class="hljs-comment"># Simulating database query</span>
    <span class="hljs-keyword">await</span> asyncio.sleep(<span class="hljs-number">0.5</span>)
    <span class="hljs-keyword">return</span> {<span class="hljs-string">'preferences'</span>: <span class="hljs-string">'theme:dark'</span>, <span class="hljs-string">'notifications'</span>: <span class="hljs-literal">True</span>}

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_complete_user_data</span>(<span class="hljs-params">user_id</span>):</span>
    api_data, db_data = <span class="hljs-keyword">await</span> asyncio.gather(
        fetch_user_api(user_id),
        query_database(user_id)
    )
    <span class="hljs-keyword">return</span> {**api_data, **db_data}
</code></pre>
<p>This gives a thorough look at how concurrency works in practice.</p>
<h3 id="heading-when-implementing-parallelism">When Implementing Parallelism</h3>
<p>Before committing parallelism into your system, you’ll need to profile the system and make sure that what causes your bottleneck is CPU-bound computation. Many developers think that their code requires parallelism when it should actually employ concurrency.</p>
<p>You can use profiling tools such as Python cProfile or line profilers to determine where time is being used or wasted in your program. When the time spent in computational loops is as large as compared to waiting in I/O, then parallelism can be beneficial.</p>
<p>To take an example, when processing images, the execution time in pixel manipulation algorithms consumes 90% of the execution time. This is a good sign that parallelism would be useful.</p>
<p>Deciding how to partition the work between multiple processors is sometimes a complex issue that you should consider carefully (in terms of dividing tasks into independent points). These chunks should be able to be processed individually without needing to communicate with each other on a regular basis.</p>
<p>Imagine that you have to examine the log files of several servers. Processing each file may happen on a different core, and the results will get added at the final stage.</p>
<p>Here's how you might structure this:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> multiprocessing <span class="hljs-keyword">import</span> Pool
<span class="hljs-keyword">import</span> re

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">analyze_log_file</span>(<span class="hljs-params">filepath</span>):</span>
    error_count = <span class="hljs-number">0</span>
    <span class="hljs-keyword">with</span> open(filepath, <span class="hljs-string">'r'</span>) <span class="hljs-keyword">as</span> f:
        <span class="hljs-keyword">for</span> line <span class="hljs-keyword">in</span> f:
            <span class="hljs-keyword">if</span> re.search(<span class="hljs-string">r'ERROR|CRITICAL'</span>, line):
                error_count += <span class="hljs-number">1</span>
    <span class="hljs-keyword">return</span> filepath, error_count

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    log_files = [<span class="hljs-string">'server1.log'</span>, <span class="hljs-string">'server2.log'</span>, <span class="hljs-string">'server3.log'</span>, <span class="hljs-string">'server4.log'</span>]

    <span class="hljs-keyword">with</span> Pool(processes=<span class="hljs-number">4</span>) <span class="hljs-keyword">as</span> pool:
        results = pool.map(analyze_log_file, log_files)

    <span class="hljs-keyword">for</span> filepath, count <span class="hljs-keyword">in</span> results:
        print(<span class="hljs-string">f'<span class="hljs-subst">{filepath}</span>: <span class="hljs-subst">{count}</span> errors found'</span>)
</code></pre>
<p>In this example, each log file is processed entirely on one core without needing to communicate with other processes until the final result aggregation.</p>
<h2 id="heading-tools-and-technologies-by-language">Tools and Technologies by Language</h2>
<p>Various programming languages offer different methods of achieving concurrency and parallelism with their own advantages and disadvantages. And when you understand the available tools in your language of choice, you’ll be able to make a wise architectural choice.</p>
<h3 id="heading-python">Python</h3>
<p>Python has a concurrent and parallel environment. For concurrent programming, the asyncio library offers a more modern syntax of async/await that’s ideal in I/O-bound tasks such as web scraping or API communication.</p>
<p>The threading module allows shared memory execution, but is restricted on CPU-bound tasks by the Global Interpreter Lock. The concurrent futures module is a high-level interface to concurrent task execution, which can be useful when you want to parallelize I/O operations without having to write the low-level code of asynchronous operations.</p>
<p>Sometimes you’ll need actual parallelism because your job requires a lot of CPU time. Multiprocessing starts individual Python processes, which don’t use the GIL at all.</p>
<p>In the case of data science and machine learning processes, distributed parallelism is offered in libraries such as joblib, ray, and dask and can run on your laptop up to a cluster of computers.</p>
<h3 id="heading-javascript-and-nodejs">JavaScript and Node.js</h3>
<p>The event loop architecture had concurrency as its foundation in JavaScript and Node.js. Asynchronous programming is now intuitive with native syntax and Promises being used as the standard model of dealing with I/O operations (like HTTP requests or file system access).</p>
<p>JavaScript is single-threaded, and Node.js is designed to execute single-thread programs that make good use of I/O bound concurrent tasks, such as web servers, which support thousands of parallel connections.</p>
<p>In cases of actual parallelism (for example, image processing or cryptographic tasks), worker threads enable you to execute JavaScript on multiple cores. The child processes module can launch individual instances of Node.js, and the cluster module allows you to launch a pool of workers to accept incoming connections and make the most of all CPU cores in a web server.</p>
<h3 id="heading-java">Java</h3>
<p>Java has mature and battle-tested concurrency and parallelism support. CompletableFuture offers a fluent interface to asynchronous operations, so it’s easier to sequence dependent asynchronous tasks together without any callback hell.</p>
<p>The ExecutorService model also provides detailed management of thread pools and task scheduling, which is necessary in developing high performance server programs. Parallelism Java thread pools are effective at handling worker threads to execute CPU-bound tasks, whereas ForkJoinPool uses work-stealing algorithms that are useful in divide-and-conquer problems.</p>
<p>Java 8 offers parallel streams, which allow you to process collections in parallel with a minimal amount of code rewrites – but you have to pay close attention to when they actually will or will not improve performance.</p>
<h3 id="heading-go">Go</h3>
<p>Go introduced concurrency as a first-class language: goroutines and channels. Goroutines are lightweight threads controlled by the Go runtime, which means that you can run thousands or even millions of operations concurrently with minimal overhead.</p>
<p>The philosophy of communication in Channels offers a secure means of communication between goroutines, and it includes the expression "do not communicate by sharing memory; share memory by communicating." Such a design makes concurrent programming more user-friendly and error-free.</p>
<p>In parallelism, Go automatically allocates goroutines to multiple CPU cores according to the GOMAXPROCS environment variable, and parallel execution is achieved automatically. This renders Go especially effective in the construction of parallel systems such as web servers, network tools, and distributed systems.</p>
<h3 id="heading-rust">Rust</h3>
<p>Rust provides concurrent and parallel programming with memory safety without performance degradation. The ownership system of the language eliminates all forms of data races at compile-time, which means that the entire category of concurrency bugs found in other languages doesn’t exist.</p>
<p>In the case of async operations, you can apply the syntax of Rust to operations of an asynchronous type with runtime libraries such as tokio or async-std and achieves similar performance to C++ without sacrificing safety.</p>
<p>The Rayon library makes parallelism of data exceedingly easy. At times, you can parallelise a calculation by substituting .iter() with .par_iter(). Rust thread pools and channels give you low-level control where necessary, and the type system keeps the threads safe, making sure that problems don’t arise in your code.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Concurrency and parallelism represent fundamental pillars of modern computing architecture. They are not interchangeable buzzwords, but are rather distinct paradigms that address different challenges:</p>
<p>Concurrency focuses on program structure and efficient task coordination. It allows systems to handle multiple operations within overlapping time periods, maximizing resource utilization and responsiveness.</p>
<p>Parallelism focuses on computational throughput and execution speed. It divides work across multiple processors to complete tasks faster through simultaneous execution.</p>
<p>The most powerful systems strategically combine both approaches, applying each where it provides the greatest benefit.</p>
<p>The next time you face a performance challenge, ask yourself these critical questions:</p>
<ol>
<li><p>Is my bottleneck caused by waiting (I/O-bound) or by computation (CPU-bound)?</p>
</li>
<li><p>Am I trying to handle more tasks simultaneously or complete tasks faster?</p>
</li>
<li><p>Do I need better resource utilisation or raw computational throughput?</p>
</li>
</ol>
<p>Your answers will guide you toward the right solution. Understanding when to apply concurrency, when to leverage parallelism, and when to combine them is what separates adequate solutions from exceptional ones. This knowledge empowers you to build systems that are not only fast but also efficient, scalable, and economically viable.</p>
<p>Master these concepts, and you will find yourself equipped to tackle increasingly complex engineering challenges with confidence and precision.</p>
<h3 id="heading-further-learning-resources">Further Learning Resources</h3>
<ul>
<li><p><a target="_blank" href="https://www.youtube.com/watch?v=f6kdp27TYZs">"Go Concurrency Patterns" by Rob Pike (Google Tech Talk)</a></p>
</li>
<li><p><a target="_blank" href="https://www.youtube.com/watch?v=oV9rvDllKEg&amp;utm_source=chatgpt.com">"Concurrency is not Parallelism" by Rob Pike</a></p>
</li>
<li><p><a target="_blank" href="https://docs.python.org/3/library/asyncio.html">Python AsyncIO Official Documentation</a></p>
</li>
<li><p><a target="_blank" href="https://realpython.com/python-concurrency/">Real Python: Concurrency and Parallelism in Python</a></p>
</li>
<li><p><a target="_blank" href="https://jcip.net/?utm_source=chatgpt.com">Java Concurrency in Practice by Brian Goetz</a></p>
</li>
<li><p><a target="_blank" href="https://spark.apache.org/docs/latest/">Apache Spark Documentation for Big Data Parallelism</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How the Node.js Event Loop Works ]]>
                </title>
                <description>
                    <![CDATA[ The Node.js event loop is a concept that may seem difficult to understand at first. But as with any seemingly complex subject, the best way to understand it is often through an analogy. In this article, you’ll learn how overworked managers, busy wait... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-the-nodejs-event-loop-works/</link>
                <guid isPermaLink="false">68b86cca911797ceb3fd37e0</guid>
                
                    <category>
                        <![CDATA[ Node.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Event Loop ]]>
                    </category>
                
                    <category>
                        <![CDATA[ asynchronous ]]>
                    </category>
                
                    <category>
                        <![CDATA[ synchronous ]]>
                    </category>
                
                    <category>
                        <![CDATA[ concurrency ]]>
                    </category>
                
                    <category>
                        <![CDATA[ parallelism ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Amanda Ene Adoyi ]]>
                </dc:creator>
                <pubDate>Wed, 03 Sep 2025 16:28:58 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1756916907320/01074df6-0f8e-4a63-9a3e-07c8297fc22b.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The Node.js event loop is a concept that may seem difficult to understand at first. But as with any seemingly complex subject, the best way to understand it is often through an analogy.</p>
<p>In this article, you’ll learn how overworked managers, busy waiters, and train stations can help bring home the fundamental concept of the event loop. If you’re working with Node, you’ll need to understand how the event loop works, as it lies at the root of some of the most powerful applications today.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-are-synchronous-and-asynchronous-code">What are Synchronous and Asynchronous Code?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-concurrency-and-parallelism-mean">What Concurrency and Parallelism Mean</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-concurrency-in-nodejs">Concurrency in Node.js</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-parallelism-in-nodejs">Parallelism in Node.js</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-the-event-loop">What is the Event Loop?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-phases-of-the-event-loop">The Phases of the Event Loop</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>In order to seamlessly follow along with this article, it would help if you are familiar with the following concepts:</p>
<ol>
<li><p><strong>A basic understanding of JavaScript:</strong> Node.js runs on JavaScript, so you’ll need to understand variables, functions, and control flow.</p>
</li>
<li><p><strong>Familiarity with Node.js basics:</strong> Running simple scripts with Node and requiring modules.</p>
</li>
<li><p><strong>Some exposure to asynchronous patterns:</strong> Knowing what patterns such as <code>setTimeout()</code> do.</p>
</li>
<li><p><strong>Some familiarity with basic CPU concepts (cores and threads):</strong> This will help you better understand concurrency and parallelism.</p>
</li>
<li><p><strong>Awareness of promises and async/await:</strong> This is optional and not a strict requirement, but will be helpful.</p>
</li>
</ol>
<h2 id="heading-what-are-synchronous-and-asynchronous-code">What are Synchronous and Asynchronous Code?</h2>
<p>When writing code for Node.js applications, there are two different ways it can run: synchronous (sync) and asynchronous (async). Synchronous code is referred to as <em>blocking</em> because when it runs, no other code runs until execution is complete.</p>
<p>An analogy for this is a busy restaurant. Picture a waiter who refuses to wait on other tables until the table they’re presently serving has received their orders and has started eating. While the food is being prepared, the waiter waits around doing nothing and only approaches your table to take your order when they are completely finished with the previous table. Needless to say, the waiter may not receive a great tip for that service.</p>
<p>This is what synchronous code is. It halts the execution of other processes until it’s complete. You can see how it works in the example below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> syncWaiter = <span class="hljs-function">(<span class="hljs-params">name</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${name}</span> attends to tables pretty slowly.`</span>);
};

syncWaiter(<span class="hljs-string">"Devin"</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"At least all the orders are correct!"</span>);
</code></pre>
<p>The code above will be run in sequence, in the order it appears.</p>
<p>Asynchronous code, unlike synchronous code, doesn’t halt all other processes until one task is executed – rather, it proceeds to carry out other tasks while a longer process runs in the background.</p>
<p>Using our waiter analogy, in this case the waiter in the restaurant would go take an order from one table, pass the order to the kitchen, and while it’s being prepared, proceeds to your table to take your order as well. This way, the waiter is able to ensure different processes are started even if one process takes a bit longer than the rest. Check out the example below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> asyncWaiter = <span class="hljs-function">(<span class="hljs-params">name</span>) =&gt;</span> {
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">()=&gt;</span> {<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${name}</span> attends to tables pretty quickly.`</span>)}, <span class="hljs-number">3000</span>)
};

asyncWaiter(<span class="hljs-string">"James"</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Wow! All the tables are attended to in a short time."</span>);
</code></pre>
<p>Unlike synchronous code, this code does run the function <code>asyncWaiter()</code> – but the callback inside the function executes later. When the duration elapses, the result is then shown on the screen. This is why asynchronous programs are referred to as <em>non-blocking.</em> They don’t halt the program, but move from one available task to another.</p>
<p>The code above returns the following:</p>
<pre><code class="lang-bash">Wow! All the tables are attended to <span class="hljs-keyword">in</span> a short time.
James attends to tables pretty quickly.
</code></pre>
<p>This print order happens because of how the <em>event loop</em> manages tasks: the synchronous <code>console.log()</code> that comes after <code>asyncWaiter()</code> runs immediately, while the asynchronous callback inside <code>asyncWaiter()</code> (from <code>setTimeout</code>) is scheduled to run later. If you don’t understand this just yet, don’t worry as I’ll break it down in detail shortly.</p>
<h2 id="heading-what-concurrency-and-parallelism-mean">What Concurrency and Parallelism Mean</h2>
<p>Node.js is single-threaded but often gives the appearance of a multi-threaded environment due to how it handles concurrency and parallelism. A thread is a single sequence of instructions executed by the CPU independently. Think of it like a single waiter named James in a restaurant.</p>
<p>If James handles multiple tasks around the same time and quickly, an onlooker outside the restaurant who sees the number of customers moving in and out of the restaurant may assume that there are a ton of waiters serving tables. In reality, James just handles his tasks asynchronously.</p>
<p>Before grasping the concept of the event loop, it’s good to understand what concurrency and parallelism are, as they help explain this.</p>
<h3 id="heading-concurrency-in-nodejs">Concurrency in Node.js</h3>
<p>Concurrency means having multiple processes run around the same time. In the waiter analogy, it is like James carrying out different tasks, though not simultaneously. He could, for instance take an order from a table and, while waiting for the food to arrive, request that extra salt be provided to another table. While the salt is on its way, he uses the waiting time to read the bill to a third table.</p>
<p>The key idea is that James never sits idle — he works on other tasks while waiting for one to finish. If this sounds an awful lot like asynchronous programming, it is because asynchronous code is just one way to achieve concurrency.</p>
<p>Other ways to execute concurrency are <a target="_blank" href="https://www.freecodecamp.org/news/multithreading-for-beginners/">multithreading</a> on a single CPU core and <a target="_blank" href="https://www.freecodecamp.org/news/how-to-handle-concurrency-in-go/">coroutines</a> which are just functions that pause their execution to resume at a later time.</p>
<h3 id="heading-parallelism-in-nodejs">Parallelism in Node.js</h3>
<p>Parallelism, on the other hand, also means having several tasks run at the same time – but instead of the tasks just being processed around the same time, they are executed at exactly the same time, simultaneously. In this case, the restaurant manager decides to hire multiple waiters and each table has a waiter who is taking orders at exactly the same time.</p>
<p>Parallelism can be achieved using multithreading on multiple CPU cores. In this setup, the threads share the same memory and run simultaneously while using clusters which run independently – each with its own memory space. Here’s a clear example of parallelism using the <code>worker_threads</code> module:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> { Worker}  = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>);

<span class="hljs-keyword">new</span> Worker(<span class="hljs-string">'./worker.js'</span>);
<span class="hljs-keyword">new</span> Worker(<span class="hljs-string">'./worker.js'</span>);
<span class="hljs-keyword">new</span> Worker(<span class="hljs-string">'./worker.js'</span>);

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Main thread keeps running in the process..."</span>);
</code></pre>
<p>The code above creates three worker threads in parallel on a multi-core machine. This doesn’t stop the main thread which continues to run, allowing each worker thread independently do its task. <code>worker.js</code> could be a simple file carrying out any task. In this case, it simply logs a message to the screen:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"This worker thread is running here!"</span>);
</code></pre>
<p>Note that the argument for the <code>Worker</code> constructor can be any file path, and the order in which they are executed isn’t dependent on the order they appear in code. Each worker runs independently of the others and they run in parallel.</p>
<p>Concurrency and parallelism allow Node.js (which is single-threaded) to appear to manage multiple tasks simultaneously. Understanding these concepts sets the stage for the event loop, showing how Node.js manages to give the appearance of concurrency while still executing code in a single-threaded environment.</p>
<h2 id="heading-what-is-the-event-loop">What is the Event Loop?</h2>
<p>The event loop listens for events in the Node.js environment. It essentially listens for actions and then processes tasks or outputs values.</p>
<p>To better understand how this works, you can picture the Node.js environment as a fast-paced organization and the event loop as an overworked manager who refuses to hire a personal assistant. The manager oversees the operations of the entire office, and has a dedicated desk that contains whatever they are working on at that particular time. Let’s call this desk <em>the call stack</em>.</p>
<p>The call stack consists of whatever processes or tasks that Node.js is currently working on. When input is entered or code is written to do something, it gets moved to the call stack and from there gets executed.</p>
<p>The order in which this execution takes place is important, as synchronous code makes it to the call stack before asynchronous code. What happens to the asynchronous code you may ask? It goes into something known as the callback queue first before ending up on the call stack.</p>
<p>The callback queue is a lineup of asynchronous tasks that make it to the call stack only if the stack is empty. You can think of it like a file cabinet in the office, where asynchronous code that is processed by a specialized team of workers under the manager go to stay until the manager’s desk is cleared. The manager only heads to the cabinet when they’re done handling all the synchronous task on the call stack. This specialized team that handles asynchronous code like callbacks and async/await are the Node APIs or the Web APIs.</p>
<p>Node or Web APIs process asynchronous code. When the code comes in, it’s processed here and then placed in the callback queue for the event loop to pick up and take to the call stack. But there are some asynchronous tasks that are prioritized. These are known as microtasks, such as <a target="_blank" href="https://www.freecodecamp.org/news/guide-to-javascript-promises/">promises</a>.</p>
<p>Microtasks are given particular priority and are queued in a special microtask queue. This is usually checked after an operation before checking the callback queue. If nothing is present, the event loop checks the callback queue but if some task exists such as <code>process.nextTick()</code>, it gets handled immediately. Macrotasks consist of tasks that are regularly scheduled and handled by the event loop only after the microtasks are treated, such as <code>setTimeout()</code> and <code>setInterval()</code><em>.</em></p>
<p>So as you can see, the event loop is basically what it sounds like – a loop. It looks through events and handles tasks based on a prioritized schedule.</p>
<p>One thing to note, though, is that even within callback queues and microtask queues, there are phases. The event loop, for instance, must handle certain tasks before others even within the same category. This is where the phases of the event loop come in.</p>
<h2 id="heading-the-phases-of-the-event-loop">The Phases of the Event Loop</h2>
<p>By analogy, the event loop is akin to a manager who checks the status of projects and tasks at regular intervals. In this case, they have a specific schedule for checking the status of projects. Some projects or tasks take priority over others, and the manager has to look through them in a set order.</p>
<p>You can also visualize event loop phases as a train moving from station to station. It starts from one location and moves to others in a particular order until it’s complete, then starts the journey again. This arrangement determines what tasks get executed before others.</p>
<p>Here are the phases of the event loop in order:</p>
<ol>
<li><p>The timers phase: This phase executes the <code>setTimeout()</code> and <code>setInterval()</code> callbacks after the duration is run. The event loop starts here, like the first station on a train’s journey.</p>
</li>
<li><p>The pending callbacks phase: These are system-level callbacks, checked after the timers phase operations.</p>
</li>
<li><p>The poll phase: This phase handles input/output (I/O) events and executes the callbacks. In the absence of callbacks, the event loop waits for new ones here.</p>
</li>
<li><p>The check phase: This phase executes <code>setImmediate()</code> callbacks.</p>
</li>
<li><p>Close callbacks: This phase is concerned with executing close events like socket closes.</p>
</li>
</ol>
<p>These callback events are checked in order and run accordingly, so that if <code>setTimeout()</code> and <code>setImmediate()</code> are in the same code, <code>setTimeout()</code> runs first unless the “train” is say, in the Poll Phase of the loop so that <code>setImmediate()</code> runs before <code>setTimeout()</code>.</p>
<p>You can see this illustrated with the example below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);

fs.readFile(<span class="hljs-string">'trainMap.txt'</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Train takes off"</span>);
    }, <span class="hljs-number">0</span>);
    setImmediate(<span class="hljs-function">() =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Oops! Immediate halt! There's a cat on the tracks!"</span>);
    })
});
</code></pre>
<p>You see in the code above that the callbacks are handled asynchronously. Recall that the event loop waits for new callbacks in the poll phase. What this means is that since <code>fs.readfile()</code> is a callback, it gets processed in the poll phase.</p>
<p><code>setTimeout()</code> is set to run in the timers phase but the event loop proceeds to the check phase (which comes next) where <code>setImmediate()</code> is executed. This is why <code>setImmediate()</code> runs before <code>setTimeout()</code> in this case. The event loop then continues from the check phase to the close phase, back to the timers phase, repeating this cycle continuously.</p>
<p>This explains why you see the output below printed to the screen:</p>
<pre><code class="lang-bash">Oops! Immediate halt! There<span class="hljs-string">'s a cat on the tracks!
Train takes off</span>
</code></pre>
<p>This illustrates how the event loop enforces order of execution across the different phases, ensuring that asynchronous operations run in the correct sequence.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The Node.js event loop can sometimes appear mysterious, but it really isn’t as complex as it first seems. At its core, it really is just the engine that ensures JavaScript can handle multiple tasks without freezing.</p>
<p>In this article, you’ve learnt about synchronous and asynchronous code, concurrency, parallelism, and how these concepts help explain the event loop and the phases of the event loop. Understanding how they work gives you the confidence to write asynchronous code without fear, debug more efficiently, and appreciate the power behind Node.js’s ability to handle concurrent tasks.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Handle Concurrency with Goroutines and Channels in Go ]]>
                </title>
                <description>
                    <![CDATA[ Concurrency is the ability of a program to perform multiple tasks simultaneously. It is a crucial aspect of building scalable and responsive systems.  Go's concurrency model is based on the concept of goroutines, lightweight threads that can run mult... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-handle-concurrency-in-go/</link>
                <guid isPermaLink="false">66b906aecacc627a9522d238</guid>
                
                    <category>
                        <![CDATA[ concurrency ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Go Language ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Destiny Erhabor ]]>
                </dc:creator>
                <pubDate>Fri, 10 May 2024 15:07:54 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/05/joshua-sortino-LqKhnDzSF-8-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Concurrency is the ability of a program to perform multiple tasks simultaneously. It is a crucial aspect of building scalable and responsive systems. </p>
<p>Go's concurrency model is based on the concept of goroutines, lightweight threads that can run multiple functions concurrently, and channels, a built-in communication mechanism for safe and efficient data exchange between goroutines.</p>
<p>Go's concurrency features enable developers to write programs that can:</p>
<ul>
<li>Handle multiple requests simultaneously, improving responsiveness and throughput.</li>
<li>Utilize multi-core processors efficiently, maximizing system resources.</li>
<li>Write concurrent code that is safe, efficient, and easy to maintain.</li>
</ul>
<p>Go's concurrency model is designed to minimize overhead, reduce latency, and prevent common concurrency errors like race conditions and deadlocks. </p>
<p>With Go, developers can build high-performance, scalable, and concurrent systems with ease, making it an ideal choice for building modern distributed systems, networks, and cloud infrastructure.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-case-study-a-bank-teller">Case study: A Bank Teller</a></li>
<li><a class="post-section-overview" href="#heading-sequential-processing-no-concurrency">Sequential Processing</a></li>
<li><a class="post-section-overview" href="#heading-concurrency">Concurrency</a></li>
<li><a class="post-section-overview" href="#heading-what-are-goroutines-and-channels">What are Goroutines and Channels?</a></li>
<li><a class="post-section-overview" href="#what-is-a-gourotine">What is a Goroutine?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-implement-a-goroutine">How to Implement a Goroutine</a></li>
<li><a class="post-section-overview" href="#heading-how-does-a-goroutine-work">How Does a Goroutine Work?</a></li>
<li><a class="post-section-overview" href="#heading-what-are-waitgroups">What are waitGroups?</a></li>
<li><a class="post-section-overview" href="#heading-what-are-channels">What are Channels?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-write-data-to-a-channel">How to Write Data to a Channel</a></li>
<li><a class="post-section-overview" href="#heading-how-to-read-data-from-a-channel">How to Read Data from a Channel</a></li>
<li><a class="post-section-overview" href="#heading-how-to-implement-channels-with-goroutine">How to Implement Channels with Goroutine</a></li>
<li><a class="post-section-overview" href="#heading-what-are-channel-buffers">What are Channel Buffers?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-an-unbuffered-channel">What is an Unbuffered Channel?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-a-buffered-channel">How to Create a Buffered Channel</a></li>
<li><a class="post-section-overview" href="#heading-what-are-channel-directions">What are Channel Directions?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-handle-multiple-communication-operations-with-channel-select">How to Handle Multiple Communication Operations with Channel Select</a></li>
<li><a class="post-section-overview" href="#how-to-timeout-long-running-process-in-a-channel">How to Timeout Long Running Processes in a Channel</a></li>
<li><a class="post-section-overview" href="#heading-how-to-close-a-channel">How to Close a Channel</a></li>
<li><a class="post-section-overview" href="#heading-how-to-iterate-over-channel-messages">How to Iterate Over Channel Messages</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<p>Let's consider a scenario to illustrate concurrency:</p>
<h2 id="heading-case-study-a-bank-teller">Case Study: A Bank Teller</h2>
<p>Imagine a busy bank with two tellers, Maria and David. Customers arrive at the bank to conduct various transactions like deposits, withdrawals, and transfers. The goal is to serve customers quickly and efficiently.</p>
<h3 id="heading-sequential-processing-no-concurrency">Sequential Processing (No Concurrency)</h3>
<p>Maria and David work sequentially, one at a time. When a customer arrives, Maria helps the customer, and David waits until Maria is finished before helping the next customer. This leads to a long wait time for customers.</p>
<h3 id="heading-concurrency">Concurrency</h3>
<p>Maria and David work concurrently, serving customers simultaneously. When a customer arrives, Maria helps the customer with a transaction, and David simultaneously helps another customer with a different transaction. They work together, sharing resources like the bank's database and cash supplies, to serve multiple customers at the same time.</p>
<p>In this scenario, concurrency enables Maria and David to work together efficiently, serving multiple customers simultaneously, and improving the overall customer experience. This same concept applies to computer programming, where concurrency enables multiple tasks to run simultaneously, improving responsiveness, efficiency, and performance.</p>
<h2 id="heading-what-are-goroutines-and-channels">What are Goroutines and Channels?</h2>
<p>A goroutine is a lightweight thread managed by the Go runtime. It is a function that runs on the Go runtime. It helps address concurrency and async flow requirements.</p>
<p>Goroutines allow you to start up and run other threads of execution concurrently within your program.</p>
<p>Channels are used to communicate between goroutines. It is a typed conduit through which you can send and receive values with the channel operator: <code>&lt;-</code>.</p>
<h3 id="heading-how-to-implement-a-goroutine">How to Implement a Goroutine</h3>
<p>To use and implement a <code>goroutine</code>, the <code>go</code> keyword is used to precede a function.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
  <span class="hljs-string">"fmt"</span>
  <span class="hljs-string">"math/rand"</span>
  <span class="hljs-string">"time"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">pause</span><span class="hljs-params">()</span></span> {
  time.Sleep(time.Duration(rand.Intn(<span class="hljs-number">1000</span>)) * time.Millisecond)
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">sendMsg</span><span class="hljs-params">(msg <span class="hljs-keyword">string</span>)</span></span> {
  pause()
  fmt.Println(msg)
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
  sendMsg(<span class="hljs-string">"hello"</span>) <span class="hljs-comment">// sync</span>

  <span class="hljs-keyword">go</span> sendMsg(<span class="hljs-string">"test1"</span>) <span class="hljs-comment">// async</span>
  <span class="hljs-keyword">go</span> sendMsg(<span class="hljs-string">"test2"</span>) <span class="hljs-comment">// async</span>
  <span class="hljs-keyword">go</span> sendMsg(<span class="hljs-string">"test3"</span>) <span class="hljs-comment">// async</span>

  sendMsg(<span class="hljs-string">"main"</span>) <span class="hljs-comment">// sync</span>

  time.Sleep(<span class="hljs-number">2</span> * time.Second)
}
</code></pre>
<p>From the example above,</p>
<ul>
<li>The <code>sendMsg</code> function is called synchronously and asynchronously.</li>
<li>The <code>sendMsg</code> function is called synchronously when the <code>sendMsg</code> function is called without the <code>go</code> keyword.</li>
<li>The <code>sendMsg</code> function is called asynchronously when the <code>sendMsg</code> function is called with the <code>go</code> keyword.</li>
</ul>
<h3 id="heading-how-does-a-goroutine-work">How Does a Goroutine Work?</h3>
<p>When the <code>sendMsg</code> function is called with the <code>go</code> keyword, the <code>main</code> function will not wait for the <code>sendMsg</code> function to finish executing before it continues to the next line of code and will return immediately after the <code>sendMsg</code> function is called.</p>
<p>Otherwise, the function is called synchronously, and the <code>main</code> function will wait for the <code>sendMsg</code> function to finish executing before it continues to the next line of code.</p>
<p>The order of the output when you run the above example will differ from the order of the code because the three <code>goroutine</code> all run concurrently and since the functions pause for a period of time, the order which they wake will differ and be outputted.</p>
<p>The <code>time.Sleep(2 * time.Second)</code> is a quick and simple method used to keep the main function running for 2 seconds to allow the <code>goroutine</code> to finish executing before the main function exits. Otherwise, the main function will exit immediately after the <code>goroutine</code> is called and the <code>goroutine</code> will not have enough time to finish executing resulting to errors.</p>
<h3 id="heading-what-are-waitgroups">What are WaitGroups?</h3>
<p>Unlike the <code>time.Sleep(2 * time.Second)</code> used in the example above, the <code>WaitGroups</code> are more standard to wait for a collection of goroutines to finish executing. It is a simple way to synchronize multiple goroutines.</p>
<p>A goroutine can also be declared with anonymous functions</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
  <span class="hljs-string">"fmt"</span>
  <span class="hljs-string">"sync"</span>
  <span class="hljs-string">"time"</span>
  <span class="hljs-string">"math/rand"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">pause</span><span class="hljs-params">()</span></span> {
  time.Sleep(time.Duration(rand.Intn(<span class="hljs-number">1000</span>)) * time.Millisecond)
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">sendMsg</span><span class="hljs-params">(msg <span class="hljs-keyword">string</span>, wg *sync.WaitGroup)</span></span> {
  <span class="hljs-keyword">defer</span> wg.Done()
  pause()
  fmt.Println(msg)
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
  <span class="hljs-keyword">var</span> wg sync.WaitGroup

  wg.Add(<span class="hljs-number">3</span>)

  <span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(msg <span class="hljs-keyword">string</span>)</span></span> {
    <span class="hljs-keyword">defer</span> wg.Done()
    pause()
    fmt.Println(msg)
  }(<span class="hljs-string">"test1"</span>)


  <span class="hljs-keyword">go</span> sendMsg(<span class="hljs-string">"test2"</span>, &amp;wg)
  <span class="hljs-keyword">go</span> sendMsg(<span class="hljs-string">"test3"</span>, &amp;wg)

  wg.Wait()
}
</code></pre>
<p>From the example above, the <strong><code>sync.WaitGroup</code></strong> is used to wait for the three <code>goroutine</code> to finish executing before the main function exits. It synchronizes the three <code>goroutine</code> and the main function.</p>
<ul>
<li>The <strong><code>sync.WaitGroup (wg)</code></strong> manages the goroutines and keeps track of the number of goroutines that are running.</li>
<li>The <strong><code>sync.WaitGroup.Add (wg.Add)</code></strong> method is used to add the number of goroutines as arguments that are running.</li>
<li>The <strong><code>sync.WaitGroup.Done (wg.Done)</code></strong> method is used to decrement the number of goroutines that are running.</li>
<li>The <code>**sync.WaitGroup.Wait (wg.Wait)**</code> method is used to wait for all the goroutines to finish executing before the main function exits.</li>
</ul>
<h2 id="heading-what-are-channels">What are Channels?</h2>
<p>Channels are used to communicate between goroutines. It is a typed conduit through which you can send and receive messages with the channel operator, <code>**&lt;-**</code>.</p>
<p>In their simplest form, one goroutine writes messages into the channel and another goroutine reads the same messages out of the channel.</p>
<p>Channels are created using the <code>make</code> method and the <code>chan</code> keyword together with its type. Channels are used to transfer messages of which type it was declared with.</p>
<p>Example:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>{
    msgChan := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>)
}
</code></pre>
<p>The example above creates a channel <code>msgChan</code> of type <code>string</code>.</p>
<h3 id="heading-how-to-write-data-to-a-channel">How to Write Data to a Channel</h3>
<p>To write data to a channel, first specify the name (<code>msgChan</code>) of the channel, followed by the <code>&lt;-</code> operator and the message. This is considered the <strong>Sender.</strong></p>
<pre><code class="lang-go">msgChan &lt;- <span class="hljs-string">"hello world"</span>
</code></pre>
<h3 id="heading-how-to-read-data-from-a-channel">How to Read Data from a Channel</h3>
<p>To read data from a channel, simple move the operator (<code>&lt;-</code>) to front of the channel name (<code>msgChan</code>) and you can assign it to a variable. This is considered the <strong>Receiver.</strong></p>
<pre><code class="lang-go">msg := &lt;- msgChan
</code></pre>
<h3 id="heading-how-to-implement-channels-with-goroutine">How to Implement Channels with Goroutine</h3>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
  <span class="hljs-string">"fmt"</span>
  <span class="hljs-string">"math/rand"</span>
  <span class="hljs-string">"time"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {

  msgChan := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>)

  <span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> {
    time.Sleep(time.Duration(rand.Intn(<span class="hljs-number">1000</span>)) * time.Millisecond)
    msgChan &lt;- <span class="hljs-string">"hello"</span> <span class="hljs-comment">// Write data to the channel</span>
    msgChan &lt;- <span class="hljs-string">"world"</span> <span class="hljs-comment">// Write data to the channel</span>
  }()

  msg1 := &lt;- msgChan
  msg2 := &lt;- msgChan

  fmt.Println(msg1, msg2)
}
</code></pre>
<p>The example above shows how to write and read data from a channel. The <code>msgChan</code> channel is created and the <code>go</code> keyword is used to create a goroutine that writes data to the channel. The <code>msg1</code> and <code>msg2</code> variables are used to read data from the channel.</p>
<p>Channels behave as a <code>first-in-first-out</code> queue. So, when one goroutine writes data to the channel, the other goroutine reads the data from the channel in the same order it was written.</p>
<h2 id="heading-what-are-channel-buffers">What are Channel Buffers?</h2>
<p>Channels can be <code>buffered</code> or <code>unbuffered</code>. The previous examples include the use of an unbuffered channels.</p>
<h3 id="heading-what-is-an-unbuffered-channel">What is an Unbuffered Channel?</h3>
<p>An unbuffered channel causes the sender to block immediately after sending a message into the channel until the receiver receives the message.</p>
<h3 id="heading-what-is-a-buffered-channel">What is a Buffered Channel?</h3>
<p>A buffered channel allows the sender to send messages into the channel without blocking until the buffer is full. So, the sender blocks only once the buffer has filled up and waits until another goroutine reads off the channel, making sure the space size becomes available before unblocking.</p>
<h3 id="heading-how-to-create-a-buffered-channel">How to Create a Buffered Channel</h3>
<p>When creating a buffered channel, use the <code>make</code> function and specify a second parameter to indicate the buffer size.</p>
<pre><code class="lang-go">msgBufChan := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>, <span class="hljs-number">2</span>)
</code></pre>
<p>The example above creates a buffered channel <code>msgBufChan</code> of type <code>string</code> with a buffer size of 2. This means that the channel can hold up to two messages before it blocks.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
  <span class="hljs-string">"time"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
  size := <span class="hljs-number">3</span>
  msgBufChan := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">int</span>, size)

  <span class="hljs-comment">// reader (receiver)</span>
  <span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">for</span> {
      _ = &lt;- msgBufChan
      time.Sleep(time.Second)
    }
  }()

  <span class="hljs-comment">//writer (sender)</span>
  writer := <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt;=&gt; <span class="hljs-number">10</span>; i++ {
      msgBufChan &lt;- i
      <span class="hljs-built_in">println</span>(i)
    }
  }

  writer()
}
</code></pre>
<p>The example above creates a buffered channel <code>msgBufChan</code> of type <code>int</code> with a buffer size of 3.</p>
<ul>
<li>The <code>writer</code> function writes data to the channel and the <code>reader</code> function reads data from the channel.</li>
<li>When the program runs, you will see that the number <code>0 through to 3</code> printed out immediately and the remaining numbers <code>5 through to 10</code> are printed out slowly about one per second (<code>time.Sleep(time.Second</code>).</li>
<li>This is showing the effect of buffered channel that specify the size it can hold before it blocks.</li>
</ul>
<h2 id="heading-what-are-channel-directions">What are Channel Directions?</h2>
<p>When using channels as function parameters, by default, you can send and receive messages within the function. To provide additional safety at compile time, channel function parameters can be defined with a direction. That is, they can be defined to be <strong>read-only</strong> or <strong>write-only</strong>.</p>
<p>Example:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
  <span class="hljs-string">"fmt"</span>
  <span class="hljs-string">"time"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">writer</span><span class="hljs-params">(channel <span class="hljs-keyword">chan</span>&lt;- <span class="hljs-keyword">string</span>, msg <span class="hljs-keyword">string</span>)</span></span> {
  channel &lt;- msg
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">reader</span><span class="hljs-params">(channel &lt;-<span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>)</span></span> {
  msg := &lt;- channel
  fmt.Println(msg)
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
  msgChan := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>, <span class="hljs-number">1</span>)

  <span class="hljs-keyword">go</span> reader(msgChan)


  <span class="hljs-keyword">for</span> i :- <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++ {
    writer(msgChan, fmt.Sprintf(<span class="hljs-string">"msg %d"</span>, i))
  }

  time.Sleep(time.Second * <span class="hljs-number">5</span>)
}
</code></pre>
<p>The example above shows how to define a channel with a direction.</p>
<ul>
<li>The <code>writer</code> function is defined with a write-only channel and</li>
<li>The <code>reader</code> function is defined with a read-only channel.</li>
</ul>
<p>The <code>msgChan</code> channel is created with a buffer size of 1. The <code>writer</code> function writes data to the channel and the <code>reader</code> function reads data from the channel.</p>
<h2 id="heading-how-to-handle-multiple-communication-operations-with-channel-select">How to Handle Multiple Communication Operations with Channel Select</h2>
<p>The <code>select</code> statement lets a goroutine wait on multiple communication operations. A <code>select</code> blocks until one of its cases can run, then it executes that case. It chooses one at random if multiple are ready.</p>
<p>The <code>select</code> and <code>case</code> statements are used to simplify the management and readability of <code>wait</code> across multiple channels.</p>
<p>Example:‌</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
  <span class="hljs-string">"fmt"</span>
  <span class="hljs-string">"time"</span>
  <span class="hljs-string">"math/rand"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">pause</span><span class="hljs-params">()</span></span> {
  time.Sleep(time.Duration(rand.Intn(<span class="hljs-number">1000</span>)) * time.Millisecond)
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test1</span><span class="hljs-params">(c <span class="hljs-keyword">chan</span>&lt;- <span class="hljs-keyword">string</span>)</span></span> {
  <span class="hljs-keyword">for</span> {
    pause()
    c &lt;- <span class="hljs-string">"hello"</span>
  }
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test2</span><span class="hljs-params">(c <span class="hljs-keyword">chan</span>&lt;- <span class="hljs-keyword">string</span>)</span></span> {
  <span class="hljs-keyword">for</span> {
    pause()
    c &lt;- <span class="hljs-string">"world"</span>
  }
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
  rand.Seed(time.Now().Unix())

  c1 := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>)
  c2 := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>)

  <span class="hljs-keyword">go</span> test1(c1)
  <span class="hljs-keyword">go</span> test2(c2)

  <span class="hljs-keyword">for</span> {
    <span class="hljs-keyword">select</span> {
    <span class="hljs-keyword">case</span> msg1 := &lt;- c1:
      fmt.Println(msg1)
    <span class="hljs-keyword">case</span> msg2 := &lt;- c2:
      fmt.Println(msg2)
    }
  }
}
</code></pre>
<p>The example above shows how to use the <code>select</code> statement to wait on multiple channels. The <code>test1</code> and <code>test2</code> functions write data to the <code>c1</code> and <code>c2</code> channels respectively. The <code>main</code> function reads data from the <code>c1</code> and <code>c2</code> channels using the <code>select</code> statement.</p>
<p>The select statement will block until one of the channels is ready to send or receive data. If both channels are ready, the select statement will choose one at random.</p>
<h2 id="heading-how-to-timeout-long-running-processes-in-a-channel">How to Timeout Long Running Processes in a Channel</h2>
<p>The <code>time.After</code> function is used to create a channel that sends a message after a specified duration. This can be used to implement a timeout for a channel.</p>
<p>It can be specified in a <code>select</code> statement to help manage situations where it's taking too long to receive a message from any of the channels being monitored.</p>
<p>Also consider using <code>timeout</code> when working with external resources as you can never guarantee the response time and, therefore may need to proactively take action after a predetermined time has passed.</p>
<p>Implementing a <code>timeout</code> with a <code>select</code> statement is very straightforward.</p>
<p>Example:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
  <span class="hljs-string">"fmt"</span>
  <span class="hljs-string">"time"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
     c1 := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>)

    <span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(channel <span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>)</span></span> {
        time.Sleep(<span class="hljs-number">1</span> * time.Second)
        channel &lt;- <span class="hljs-string">"hello world"</span>
    }(c1)

    <span class="hljs-keyword">select</span> {
    <span class="hljs-keyword">case</span> msg2 := &lt;-c1:
        fmt.Println(msg2)
    <span class="hljs-keyword">case</span> &lt;-time.After(<span class="hljs-number">2</span> * time.Second): <span class="hljs-comment">//Timeout after 2 second</span>
        fmt.Println(<span class="hljs-string">"timeout"</span>)
  }
}
</code></pre>
<ul>
<li>The example above shows how to use the <code>time.After</code> function to create a channel that sends a message after a specified duration.</li>
<li>The <code>main</code> function reads data from the <code>c1</code> channel using the <code>select</code> statement.</li>
<li>The <code>select</code> statement will block until one of the channels is ready to send or receive data.</li>
<li>If the <code>c1</code> channel is ready, the <code>main</code> function will print the message.</li>
<li>If the <code>c1</code> channel is not ready after 2 seconds, the <code>main</code> function will print a timeout message.</li>
</ul>
<h2 id="heading-how-to-close-a-channel">How to Close a Channel</h2>
<p>Closing a channel is used to indicate that no more values will be sent on the channel. It is used to signal to the receiver that the channel has been closed and no more values will be sent.</p>
<p>Go channels can be explicitly closed to help with synchronization issues. The default implementation will close the channel when all the values have been sent.</p>
<p>Closing a channel is done by invoking the built-in <code>close</code> function.‌</p>
<pre><code class="lang-go"><span class="hljs-built_in">close</span>(channel)
</code></pre>
<p>Example:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
  <span class="hljs-string">"fmt"</span>
  <span class="hljs-string">"bytes"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">process</span><span class="hljs-params">(work &lt;-<span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>, fin <span class="hljs-keyword">chan</span>&lt;- <span class="hljs-keyword">string</span>)</span></span> {
  <span class="hljs-keyword">var</span> b bytes.Buffer
  <span class="hljs-keyword">for</span> {
    <span class="hljs-keyword">if</span> msg, notClosed := &lt;-work; notClosed {
      fmt.Printf(<span class="hljs-string">"%s received...\n"</span>, msg)
    } <span class="hljs-keyword">else</span> {
      fmt.Println(<span class="hljs-string">"Channel closed"</span>)
      fin &lt;- b.String()
      <span class="hljs-keyword">return</span>
    }
  }
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
  work := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>, <span class="hljs-number">3</span>)
  fin := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>)

  <span class="hljs-keyword">go</span> process(work, fin)

  word := <span class="hljs-string">"hello world"</span>

  <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">len</span>(word); i++ {
    letter := <span class="hljs-keyword">string</span>(word[i])
    work &lt;- letter
    fmt.Printf(<span class="hljs-string">"%s sent ...\n"</span>, letters)
  }

  <span class="hljs-built_in">close</span>(work)

  fmt.Printf(<span class="hljs-string">"result: %s\n"</span>, &lt;-fin)
}
</code></pre>
<p>The example above shows how to close a channel. The <code>work</code> channel is created with a buffer size of 3. The <code>process</code> function reads data from the <code>work</code> channel and writes data to the <code>fin</code> channel. The <code>main</code> function writes data to the <code>work</code> channel and closes the <code>work</code> channel. The <code>process</code> function will print the message if the <code>work</code> channel is not closed. If the <code>work</code> channel is closed, the <code>process</code> function will print a message and write the data to the <code>fin</code> channel.</p>
<h2 id="heading-how-to-iterate-over-channel-messages">How to Iterate Over Channel Messages</h2>
<p>Channels can be iterated over by using the <code>range</code> keyword, similar to <code>arrays, slice, and/or maps</code>. This allows you to quickly and easily iterate over the messages within a channel.</p>
<p>Example:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
  <span class="hljs-string">"fmt"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
  c := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>, <span class="hljs-number">3</span>)

  <span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> {
    c &lt;- <span class="hljs-string">"hello"</span>
    c &lt;- <span class="hljs-string">"world"</span>
    c &lt;- <span class="hljs-string">"goroutine"</span>
    <span class="hljs-built_in">close</span>(c) <span class="hljs-comment">// Closing the channel is very important before proceeding to the iteration hence deadlock error</span>
  }()

  <span class="hljs-keyword">for</span> msg := <span class="hljs-keyword">range</span> c {
    fmt.Println(msg)
  }
}
</code></pre>
<p>The example above shows how to iterate over a channel using the <code>range</code> keyword. The <code>c</code> channel is created with a buffer size of 3. The <code>go</code> keyword is used to create a goroutine that writes data to the <code>c</code> channel. The <code>main</code> function iterates over the <code>c</code> channel using the <code>range</code> keyword and prints the message.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we learned how to handle concurrency with goroutines and channels in Go. We learned how to create goroutines, and how to use <code>WaitGroups</code> and channels to communicate between goroutines. </p>
<p>We also learned how to use channel buffers, channel directions, channel <code>select</code>, channel timeout, channel closing, and channel range. </p>
<p>Goroutines and channels are powerful features in Go that help address concurrency and async flow requirements.</p>
<p>As always, I hope you enjoyed the article and learned something new. If you want, you can also follow me on <a target="_blank" href="https://www.linkedin.com/in/destiny-erhabor">LinkedIn</a> or <a target="_blank" href="https://twitter.com/caesar_sage">Twitter</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Entering into the World of Concurrency with Python ]]>
                </title>
                <description>
                    <![CDATA[ In this tutorial, we will explore concurrency in Python. We'll discuss Threads and Processes and how they're similar and different. You'll also learn about Multi-threading, Multi-processing, Asynchronous Programming, and Concurrency in general in Pyt... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/concurrency-in-python/</link>
                <guid isPermaLink="false">66c4c5d21b22d2d8d9040ec1</guid>
                
                    <category>
                        <![CDATA[ concurrency ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Hemachandra Routhu ]]>
                </dc:creator>
                <pubDate>Tue, 20 Feb 2024 18:53:34 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/08/pexels-wendyaffieplaas-1212179.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this tutorial, we will explore concurrency in Python. We'll discuss Threads and Processes and how they're similar and different. You'll also learn about Multi-threading, Multi-processing, Asynchronous Programming, and Concurrency in general in Python. </p>
<p>Many tutorials discuss these concepts, but they can be challenging to grasp due to the lack of clear examples. I will guide you through the concepts and delve into the world of Concurrency in Python, providing straightforward explanations for better understanding.</p>
<h3 id="heading-prerequisites">Prerequisites</h3>
<p>You should be familiar with Python coding and have a basic understanding of multi-threading. </p>
<p>Although I have provided non-multi-threading code examples to help those who are not acquainted with these concepts, if you already have knowledge in these areas, you'll be able to gain a deeper understanding.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><a class="post-section-overview" href="#heading-sequential-programming">Sequential Programming</a></li>
<li><a class="post-section-overview" href="#heading-what-are-threads">What Are Threads</a>?</li>
<li><a class="post-section-overview" href="#heading-what-are-processes">What Are Processes</a>?</li>
<li><a class="post-section-overview" href="#heading-threads-vs-processes">Threads vs Processes</a></li>
<li><a class="post-section-overview" href="#heading-what-is-multi-threading">What is Multi-Threading</a>?</li>
<li><a class="post-section-overview" href="#heading-what-is-multi-processing">What is Multi-Processing</a>?</li>
<li><a class="post-section-overview" href="#heading-what-is-asynchronous-programming">What is Asynchronous Programming</a>?</li>
<li><a class="post-section-overview" href="#heading-what-is-concurrency">What is Concurrency</a>?</li>
<li><a class="post-section-overview" href="#heading-global-interpreter-lock-gil">Global Interpreter Lock (GIL)</a></li>
<li>How to Remove the Limitations of GIL<br>– <a class="post-section-overview" href="#heading-use-another-flavor-of-python">Using another flavor of Python</a><br>– <a class="post-section-overview" href="#heading-use-the-multiprocessing-module">Multiprocessing module</a><br>– <a class="post-section-overview" href="#heading-implement-asynchronous-programming">Asyncio</a></li>
<li><a class="post-section-overview" href="#heading-summary">Summary</a></li>
</ol>
<h2 id="heading-sequential-programming">Sequential Programming</h2>
<p>Don't be afraid when you see the word "Concurrency". Let's set it aside for now. </p>
<p>When you begin learning programming languages like Python or Java, your program usually runs in a <code>sequence</code>, starting from the top and going down.</p>
<p>For example:</p>
<pre><code class="lang-python">a = <span class="hljs-number">25</span>
b = <span class="hljs-number">30</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add</span>(<span class="hljs-params">a, b</span>):</span>
    print(<span class="hljs-string">"Addition value: "</span>, a+b)

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">sub</span>(<span class="hljs-params">a, b</span>):</span>
    print(<span class="hljs-string">"Subtraction Value: "</span>, a-b)

add(a,b)
sub(a,b)
</code></pre>
<p>When you run the program above, your Python interpreter starts executing it line by line from top to bottom in a sequence. It starts from line <code>a=25</code> and ends at the <code>sub()</code> function. </p>
<p>No matter how long your code is, Python executes it from the top. This way of executing code is also known as the <strong>top-to-bottom</strong> or <strong>sequential</strong> approach – or simply <strong>Sequential programming</strong>!</p>
<h2 id="heading-what-are-threads">What Are Threads?</h2>
<p>When you run your program, the Python interpreter creates a small program internally and instructs it to start running. This small program, created by the interpreter, is called a <strong>Thread</strong>. A thread is a small program that performs a certain task. </p>
<p>For any program or application, Python creates and instructs a thread to start execution. This thread is called the <code>Main thread</code>. It's important to note that the <code>Main thread</code> can also create multiple other threads if you tell it to do so. </p>
<p>That's correct! You can write a program to tell the Main thread to create multiple other threads that perform your tasks. So, a thread performs some work or a task (here main thread runs your program from top to bottom). </p>
<p>So you can create multiple tasks and assign one thread to perform one task. Or you can also create one thread and run multiple tasks – just like Python interpreter created <code>Main thread</code> and executed both the tasks <code>add</code> and <code>sub</code> in sequential order.</p>
<h2 id="heading-what-are-processes">What Are Processes?</h2>
<p>Imagine you own a company and have many tasks to do. To handle them, you will begin hiring people and assigning a task to each person. </p>
<p>Each person works independently on their task. They have their own set of tools and resources, and if one person finishes their task, it doesn't directly affect what the others are doing. </p>
<p>In the world of computers, each person doing a task is like a separate process. Processes are independent, have their own memory space, and don't directly share resources.</p>
<p>For instance, when you turn on your computer and begin opening a browser, notepad, and MS Office, you are essentially starting several processes. Each program you open, like the browser or notepad, is a separate process with its own memory. These processes are not connected to each other. </p>
<p>When you run a program, your operating system creates a process, assigns some memory to it, dedicates some CPU time, and executes the program within it. How the program functions within the process is determined by how it's designed. In essence, we can say that an application is a process.</p>
<h2 id="heading-threads-vs-processes">Threads vs Processes</h2>
<p>Now, that may seem confusing, right? But there is a small difference between threads and processes. Let me clarify it for you.</p>
<p>A process is like a single task performed by the operating system. It works on its own and has its own memory space.</p>
<p>A thread is like a smaller part of a task within a program. It handles small tasks. Threads are created <strong>within a process</strong> and are controlled by the program. </p>
<p>A program can create multiple threads and they can share resources, communicate with each other, but only within the same process.</p>
<p>To simplify, think of a browser as a process. Within this process, it can run single or multiple threads.</p>
<p>When you learn about concurrency in programming, you will see terms like "Multi-Threading", "Multi-Processing", "Asynchronous", and finally the big one "Concurrency". Don't let these terms intimidate you – the concepts are simpler than you think. And they're what you'll learn about next.</p>
<h2 id="heading-what-is-multi-threading">What is Multi-Threading?</h2>
<p>Life is easier when you have a lot of workers to complete all the necessary tasks, isn't it? Similarly, if you have multiple threads, they help you divide all your program tasks into smaller parts. </p>
<p>Of course, if you have a lot of workers, then it can be tough to manage them, and it costs more. These are the advantages and disadvantages to multi-threading as well.</p>
<p>Using multiple threads to perform your tasks is called <strong>multi-threading</strong>. </p>
<p>Let's revisit the example:</p>
<pre><code class="lang-python">a = <span class="hljs-number">25</span>
b = <span class="hljs-number">30</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add</span>(<span class="hljs-params">a, b</span>):</span>
    print(<span class="hljs-string">"Addition value: "</span>, a+b)

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">sub</span>(<span class="hljs-params">a, b</span>):</span>
    print(<span class="hljs-string">"Subtraction Value: "</span>, a-b)

add(a,b)
sub(a,b)
</code></pre>
<p>You can tell the Python interpreter to create two threads and execute the <code>add()</code> with thread-1 and <code>sub()</code> with thread-2. This is fine, but why would you want to do that? </p>
<p>Consider the sequential approach: the interpreter runs <code>add()</code> first, then <code>sub()</code>. Why wait for <code>sub()</code> while <code>add()</code> is running? In this case, addition and subtraction are entirely different and don't depend on each other, so why wait? Can't both functions run simultaneously? </p>
<p>This is where multiple threads come into play. If your tasks are independent and don't need to wait for one another to complete, then you have the privilege to run your tasks using multiple threads.</p>
<p>Note that whether you create one thread or more, your Python interpreter will create the <strong>main thread</strong> and handle the execution of your program. If you instruct your program to create 2 threads, the main thread will create them for you and assign which task needs to be done by each thread. </p>
<p>So, irrespective of whether you create a thread in your program or not, the main thread will be created, and it takes care of your program execution.</p>
<h2 id="heading-what-is-multi-processing">What is Multi-Processing?</h2>
<p>From the name itself, you may be able to understand that multiprocessing means running multiple processes <strong>separately</strong> without sharing resources directly. </p>
<p>For instance, imagine two restaurants, each with its own chefs. The method one chef in Restaurant 1 uses to cook a dish doesn't affect or rely on Restaurant 2. They operate independently, even if you place the same order at both restaurants.</p>
<p>But you might be wondering: how do we talk about multitasking on a computer with one processor but many CPU cores? </p>
<p>In modern computers, some processors have multiple cores, and each core works like its own processor. If a processor has 4 cores, it can handle 4 tasks simultaneously by assigning each task to a different core. This means the CPU, memory, and storage resources are shared among these tasks without them relying on each other. </p>
<p>This approach to multitasking on multiple cores within one processor is known as <strong>Symmetric Multiprocessing</strong>.</p>
<p>If you have multiple processors, you can assign each task to a different processor to execute independently. This type of multi-processing is called <strong>Distributed Multi-processing.</strong></p>
<p>I want to remind you that multi-threading occurs <strong>within</strong> a process. Simply put, multi-threading only happens within a process.</p>
<p>Let's gain a practical understanding of multiprocessing. I will be using the same example that we discussed in the Sequential Programming and Multi-threading sections, but this time using a multiprocessing version. </p>
<p>Just as you ran the program using threads, we will now run the program using processes.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> multiprocessing <span class="hljs-keyword">import</span> Process

a = <span class="hljs-number">25</span>
b = <span class="hljs-number">30</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add</span>(<span class="hljs-params">a, b</span>):</span>
    <span class="hljs-keyword">try</span>:
        print(<span class="hljs-string">"Addition value: "</span>, a + b)
        time.sleep(<span class="hljs-number">10</span>)
    <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:
        print(e)

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">sub</span>(<span class="hljs-params">a, b</span>):</span>
    <span class="hljs-keyword">try</span>:
        print(<span class="hljs-string">"Subtraction Value: "</span>, a - b)
        time.sleep(<span class="hljs-number">20</span>)
    <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:
        print(e)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    <span class="hljs-comment"># Create two processes, one for add and one for sub</span>

    add_process = Process(target=add, args=(a, b))
    sub_process = Process(target=sub, args=(a, b))

    <span class="hljs-comment"># Start the processes</span>
    add_process.start()
    sub_process.start()

    <span class="hljs-comment"># Wait for both processes to finish</span>
    add_process.join()
    sub_process.join()
</code></pre>
<p>We are using the <code>multiprocessing</code> module in this program to create 2 processes: <code>add_process</code> and <code>sub_process</code>. One process runs the <code>add()</code> function and another runs the <code>sub()</code> function, respectively. </p>
<p>We then start both the processes using the <code>.start()</code> method of both the process objects. After this, we are using the <code>.join()</code> method of the process objects to make the <code>main thread</code> wait until both processes complete.</p>
<p>Let's understand this in a bit more detail. I am running the program in a Windows operating system-based computer. Open the <code>task manager</code> application to view all the running processes in your operating system. For running your program, you have to use your Window's <code>command prompt</code> or <code>cmd</code> or your <code>terminal</code> in your Linux or Mac.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Capture1-2.PNG" alt="Image" width="600" height="400" loading="lazy">
<em>TaskManager and CMD</em></p>
<p>The image above shows task manager on the left and CMD on the right. You can easily see the Windows Command Processor, or CMD, running as a process in the task manager. You can also see that I am running <code>Google Chrome</code> and the <code>Snipping Tool</code> in the background, both of which are also listed in my Task Manager.</p>
<p>I am going to run the program now from CMD by executing the command <code>python sample.py,</code> where <code>sample</code> is the name of the program.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Capture2-1.PNG" alt="Image" width="600" height="400" loading="lazy">
<em>Running the sample.py in CMD</em></p>
<p>In the image above, I am running the program in CMD on the right. The program immediately printed the output of both the functions <code>add()</code> and <code>sub()</code>. The program is still running, because we used <code>time.sleep()</code> in both functions, which pauses the execution of the <code>add_process</code> for <strong>10</strong> seconds and <code>sub_process</code> for <strong>20</strong> seconds. </p>
<p>Setting the output aside, let's shift our focus to the Task Manager. If you expand the <code>Windows Command Processor</code>, you will find <strong>3</strong> Python processes running. Let's explore why there are three Python processes instead of two (<code>add_process</code> and <code>sub_process</code>). </p>
<p>Since we initiated the program via CMD, your Python application is triggered through the Windows Command Processor or CMD and is therefore listed under CMD. We already know that when you run a Python program, your Python interpreter starts the <code>Main Thread</code>, which manages the execution of the program. </p>
<p>This Main Thread is listed as <strong>one</strong> process. Then, as we are creating <strong>two</strong> processes within the program, they are listed as an additional two processes under the Windows Command Processor (as seen in the image above).</p>
<p>Note that both the processes are completely independent and don't share any resources. If you want to share anything between the processes then you have to implement special mechanisms like a <strong>Queue.</strong></p>
<h2 id="heading-what-is-asynchronous-programming">What is Asynchronous Programming?</h2>
<p>Asynchronous programming is a specific approach to managing tasks that involves waiting for external operations to complete. It allows a program to <strong>continue executing</strong> other tasks while <strong>waiting</strong> for these operations to finish, rather than blocking until they complete.</p>
<p>Note: If you are not familiar with Multi-threaded coding in Python, you can skip to example-2.</p>
<h3 id="heading-example-1">Example 1:</h3>
<p>Same example again, but this time the functions are executed using threads. <code>add()</code> is executed by <code>thread-1</code> and <code>sub()</code> is executed by <code>thread-2</code>. Following is the threading version of the example:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> threading
<span class="hljs-keyword">import</span> time

a = <span class="hljs-number">25</span>
b = <span class="hljs-number">30</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add</span>(<span class="hljs-params">a, b</span>):</span>
    print(<span class="hljs-string">"Inside add function\n"</span>)
    print(<span class="hljs-string">"Waiting for 20 seconds in add \n"</span>)
    time.sleep(<span class="hljs-number">20</span>)
    print(<span class="hljs-string">"Addition value:"</span>, a + b)

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">sub</span>(<span class="hljs-params">a, b</span>):</span>
    print(<span class="hljs-string">"Inside sub function\n"</span>)
    print(<span class="hljs-string">"Subtraction Value {}:"</span>.format(a - b))
    print(<span class="hljs-string">"Waiting for 10 seconds in sub\n"</span>)
    time.sleep(<span class="hljs-number">10</span>)

<span class="hljs-comment"># Create threads for add and sub functions</span>
add_thread = threading.Thread(target=add, args=(a, b))
sub_thread = threading.Thread(target=sub, args=(a, b))

<span class="hljs-comment"># Start both threads</span>
add_thread.start()
sub_thread.start()

<span class="hljs-comment"># Wait for both threads to finish</span>
add_thread.join()
sub_thread.join()

print(<span class="hljs-string">"Complete"</span>)
</code></pre>
<p>We created <code>add_thread</code> and <code>sub_thread</code> and assigned the functions <code>add</code> and <code>sub</code> as target. If you run this program, you can see the following output:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Capture3.PNG" alt="Image" width="600" height="400" loading="lazy">
<em>Program output</em></p>
<p>Let's breakdown the output:</p>
<ul>
<li>Both <code>add</code> and <code>sub</code> functions are started using separate threads (<code>add_thread</code> and <code>sub_thread</code>).</li>
<li>The <code>add</code> function prints "Inside add function" and then indicates that it is waiting for 20 seconds using <code>time.sleep(20)</code>.</li>
<li>The <code>sub</code> function prints "Inside sub function" and "Subtraction Value -5:" (result of the subtraction operation), followed by a message that it is waiting for 10 seconds using <code>time.sleep(10)</code>.</li>
<li>As the threads are running at the same time, the messages from both functions may appear interleaved, depending on the execution order of the threads.</li>
<li>After the waiting periods, both threads print the results of their respective operations. The <code>add</code> function prints "Addition value: 55," and the <code>sub</code> function prints nothing else.</li>
<li>Finally, the main program prints "Complete" once both threads have finished their execution.</li>
</ul>
<p>While the <code>add_thread()</code> is waiting for 20 seconds, your <code>sub_thread()</code> has provided the result and started to sleep for 10 seconds. Meanwhile, <code>add_thread</code> completed its wait time, computed the addition value, and printed the result. So, while one thread is waiting, your second thread started executing, and while your second thread was waiting, your first thread started running. </p>
<p>This way of managing the tasks to execute simultaneously when one task is waiting for external resources is called <strong>Asynchronous programming.</strong></p>
<p>The key point to note is that threads run simultaneously, allowing the program to perform tasks in parallel. The interleaved output demonstrates the asynchronous nature of threading, where different parts of the program can execute simultaneously. </p>
<h3 id="heading-example-2">Example 2:</h3>
<p>Let's consider two tasks: Task 1 retrieves a list of employees from a company's database, and Task 2 retrieves a list of active projects by the same company. It's clear that these tasks are not connected or dependent on each other – they are independent tasks. </p>
<p>Let's write some sample code for these tasks:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_employees</span>():</span>
    <span class="hljs-comment"># connect to the database</span>
    <span class="hljs-comment"># code to get employees list from database</span>
    <span class="hljs-keyword">return</span> employees_list

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_active_projects</span>():</span>
    <span class="hljs-comment"># connect to the database</span>
    <span class="hljs-comment"># code to get the projects under development</span>
    <span class="hljs-keyword">return</span> active_projects

<span class="hljs-comment"># run task1</span>
get_employees()

<span class="hljs-comment"># run task2</span>
get_active_projects()
</code></pre>
<p>Don't worry about the code inside the functions – we want to understand the concept here. </p>
<p>When you run the program above, the Python interpreter tells the <code>main thread</code> to execute the program step by step, starting from the top and going downwards. </p>
<p>First, it performs task-1, which let's say takes 2 seconds, and then it moves on to task-2, which let's say also takes 2 seconds. We know that these tasks are independent, so why should task-2 wait for task-1 to finish? </p>
<p>If there's a mechanism where I can tell the interpreter to start task-1 (getting a list of employees from the database), and while it waits for task-1 to complete, I can also instruct it to start task-2 (getting a list of active projects from the database), then I'm essentially executing both tasks almost simultaneously. This helps me reduce the <strong>total execution time</strong> of both tasks. This is another example of <strong>asynchronous programming</strong>.</p>
<p>Now it's clear. How do we do this? How do we ensure that task-2 runs while we're waiting for task-1 to get the list of employees from the database? We have many tools for that. <strong>Multithreading</strong> is one of them. </p>
<p>In the example above, you use two threads: thread-1 for task-1 and then immediately start thread-2 for task-2. Thread-2 doesn't have to wait for Thread-1 to finish.</p>
<p>You can also use concepts like <strong>async/await</strong>, <strong>callbacks</strong>, and <strong>promises</strong> in various programming languages to implement asynchronous programming. You can <a target="_blank" href="https://www.freecodecamp.org/news/asynchronous-programming-in-javascript-examples/">read more about those concepts in JavaScript here</a>.</p>
<h2 id="heading-what-is-concurrency">What is Concurrency?</h2>
<p>Finally, we've arrived at concurrency! </p>
<p>You should now understand that multi-threading or multi-processing involves using several threads and processes to perform multiple tasks simultaneously to decrease the time it takes for a program or application to run. </p>
<p>But how does this occur? What goes on in the background? How does the processor ensure that the threads or processes run simultaneously?</p>
<p>Imagine you have two tasks: driving a car and making a phone call. You decide to do both at once. While driving, you start calling your friend using your cell phone and speaking. </p>
<p>You're doing these tasks simultaneously, but there's a small detail that's important: your brain quickly scans the road, checks for other cars, and ensures you're focused and steady. It spends about one millisecond here, then switches to speaking with your friend, which might take another millisecond, and then shifts back to driving every millisecond. It continuously switches between both tasks. </p>
<p>As the time spent on each task is very short (just one millisecond), you might think you're doing both tasks at the same time. But there's a very tiny difference in time for each task, which makes it seem like both tasks are being done simultaneously.</p>
<p>In a similar way, when there are two tasks being executed by either two threads or two processes, your processor switches between these tasks very quickly. It runs thread-1 for 1 millisecond, then saves its state and switches to thread-2, running it for another 1 millisecond. After saving the state of thread-2, it shifts back to thread-1 and runs it for another millisecond. </p>
<p>I'm using 1 millisecond as an example, but in reality, it happens even faster. The speed of switching depends on your processor. </p>
<p>As the switching between tasks is so fast, it gives the impression that both tasks are running simultaneously. But it's important to note that even if you ask for both thread-1 and thread-2 to run at the same time, your processor and operating system decide which one to prioritize first, how much time to allocate to each, and in what order to execute them.</p>
<p>In summary, it's like juggling multiple tasks simultaneously. You start one task, switch to another when needed, and keep cycling through them until everything is done. This concept is called <strong>concurrency</strong>.</p>
<blockquote>
<p>"Concurrency is a concept of managing the progress of multiple tasks at the same time, even if they are not executing simultaneously."</p>
</blockquote>
<p>How do you achieve this? Using multi-threading and multi-processing again!<br>By now, you may have understood that Concurrency and Asynchronous Programming are the core concepts, while multi-threading and multi-processing are implementations of these concepts.</p>
<h2 id="heading-global-interpreter-lock-gil">Global Interpreter Lock (GIL)</h2>
<p>The concepts of concurrency and asynchronous programming are the same, regardless of what programming language you use. But the implementation of these concepts does depend on the programming language you choose. </p>
<p>When it comes to multi-threading, Python behaves bit weird. Let's understand this with a small example.</p>
<p>In my childhood, my younger brother and I used to play computer games. My mother made a rule that my brother should play first for 30 min and then I could play second for 30 min. This rule was to make sure that no one messed up the game by trying to do things at the same time. So I would wait for 30 min until my turn came to play the game for 30 min. </p>
<p>In the world of computers, programs are like me and my brother trying to play the game. The <strong>Global Interpreter Lock</strong> (GIL) is like the rule that only allows one, either me or my brother (or thread), to play the game (or execute Python bytecode) at a time.</p>
<p>GIL is a rule that allows only one thread at a time to run the Python bytecode. Global Interpreter Lock is a lock that protects access to Python objects, preventing multiple threads from executing Python bytecode simultaneously in a single process. This means that even in a multi-threaded Python program, only one thread can execute Python bytecode at any given time.</p>
<p>As a result, this causes performance limitations of multi-threading in <strong>CPU-bound tasks</strong>. Note that CPU-bound tasks are the tasks that rely a lot on CPU rather than IO operations. Mathematical computations, compression and decompression of files, and compilation of programs by a program compiler are a few examples of CPU-bound tasks that use more CPU. </p>
<p>Let's look at an example:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> time

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">count_up</span>():</span>
    count = <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">100000000</span>):
        count = count + i

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">count_down</span>():</span>
    count = <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">100000000</span>):
        count = count + i

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    start_time = time.time()

    count_up()
    count_down()

    end_time = time.time()

    print(<span class="hljs-string">f"Time taken: <span class="hljs-subst">{end_time - start_time}</span> seconds"</span>)
</code></pre>
<p>In the above program, we are running the <code>count_up()</code> and <code>count_down()</code> functions sequentially one after the other. The <code>count_up</code> and <code>count_down</code> functions each iterate through a large range, calculating the cumulative sum of numbers. The output of the program is:</p>
<pre><code>Time taken: <span class="hljs-number">25.86127805709839</span> seconds
</code></pre><p>Let's write the same program using multi-threading as follows:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> threading
<span class="hljs-keyword">import</span> time

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">count_up</span>():</span>
    count = <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">100000000</span>):
        count = count + i

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">count_down</span>():</span>
    count = <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">100000000</span>):
        count = count + i

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    start_time = time.time()

    <span class="hljs-comment"># Create two threads, each running a CPU-bound task</span>
    thread1 = threading.Thread(target=count_up)
    thread2 = threading.Thread(target=count_down)

    <span class="hljs-comment"># Start both threads</span>
    thread1.start()
    thread2.start()

    <span class="hljs-comment"># Wait for both threads to finish</span>
    thread1.join()
    thread2.join()

    end_time = time.time()

    print(<span class="hljs-string">f"Time taken: <span class="hljs-subst">{end_time - start_time}</span> seconds"</span>)
</code></pre>
<p>Two threads <code>thread1</code> and <code>thread2</code> are created to run the <code>count_up</code> and <code>count_down</code> functions simultaneously. The program measures the time it takes for both threads to complete using the <code>time</code> module. The output of the program is:</p>
<pre><code>Time taken: <span class="hljs-number">24.498752117156982</span> seconds
</code></pre><p>Note that in your PC, the time taken for this program to complete can be different. If you observe, the output for the <code>sequential</code> and <code>multi-threading</code> versions of the program <code>(25.8 seconds vs 24.98 seconds)</code> there is not much difference between the time taken. This is because of GIL. </p>
<p>Global Interpreter Lock (GIL) in CPython, which allows only one thread to execute Python bytecode at a time, means that the execution time <strong>won't</strong> show a significant improvement compared to running the tasks sequentially. </p>
<p>This highlights the limitation of multithreading in Python for CPU-bound tasks due to GIL.</p>
<p>But it's worth noting that while the GIL prevents multiple threads from executing Python bytecode at the same time, it does not prevent threading altogether. Python threads can still be useful for I/O-bound tasks where threads spend most of their time waiting for external operations (like network or disk I/O) rather than performing CPU-intensive computations.</p>
<p>So how do you remove the limitations of GIL?</p>
<h3 id="heading-use-another-flavor-of-python">Use another flavor of Python</h3>
<p>Python standard implementation is Cpython. This is the Python designed using the C language and is used most all over the world. To avoid GIL, we can use Jython (Python developed using Java), IronPython (Python developed using .NET), or PyPy (Python developed using Python).</p>
<p>You can check out the following resources for more info:</p>
<ul>
<li><a target="_blank" href="https://www.jython.org/">Home | Jython</a></li>
<li><a target="_blank" href="https://ironpython.net/">IronPython.net</a> </li>
<li><a target="_blank" href="https://www.pypy.org/">PyPy</a></li>
</ul>
<h3 id="heading-use-the-multiprocessing-module">Use the multiprocessing module</h3>
<p>Multiprocessing is a module that helps you take advantage of your multiple CPU cores for running your program in separate processes. </p>
<p>Each process has its own CPU core, memory, resources, and <code>interpreter</code>. Yes, every process has its own interpreter to run your Python code. If you have 4 CPU cores then you can run 4 processes, each having its own interpreter that executes your application in its own memory. </p>
<p>Let's write the program we discussed in the <strong>GIL</strong> concept using multi-processing as follows:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> multiprocessing
<span class="hljs-keyword">import</span> time

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">count_up</span>():</span>
    count = <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">100000000</span>):
        count = count + i

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">count_down</span>():</span>
    count = <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">100000000</span>):
        count = count + i

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    start_time = time.time()

    <span class="hljs-comment"># Create two threads, each running a CPU-bound task</span>
    process1 = multiprocessing.Process(target=count_up)
    process2 = multiprocessing.Process(target=count_down)

    <span class="hljs-comment"># Start both threads</span>
    process1.start()
    process2.start()

    <span class="hljs-comment"># Wait for both threads to finish</span>
    process1.join()
    process2.join()

    end_time = time.time()

    print(<span class="hljs-string">f"Time taken: <span class="hljs-subst">{end_time - start_time}</span> seconds"</span>)
</code></pre>
<p>The output for the program when you run it via your terminal or CMD is:</p>
<pre><code>Time taken: <span class="hljs-number">8.376060724258423</span> seconds
</code></pre><p>This represents a significant improvement in the time taken compared to techniques such as Sequential and Multi-threading <strong>(25.8 vs 24.4 vs 8.3 seconds)</strong>. This illustrates how using multiprocessing can help reduce your CPU time. </p>
<p>Note that there will be overhead if you want to communicate between the processes. As a result, while multiprocessing can be effective for CPU-bound tasks, it may not be suitable for all scenarios, especially those involving frequent communication or large data transfers between processes.</p>
<h3 id="heading-implement-asynchronous-programming">Implement asynchronous programming!</h3>
<p>If your program or application is not CPU bound heavy or depends more on CPU processing then using the <code>asyncio</code> module of Python, you can implement the concept of Asynchronous Programming (not waiting for task 1 to complete before starting task 2). </p>
<p>This module is mainly used in I/O operations. Asyncio allows you to write asynchronous code that cooperatively multitasks <strong>without</strong> relying on threads, which can help in situations where threads would otherwise be blocked waiting for I/O operations to complete. </p>
<p>By using asyncio, you can write non-blocking code that allows other tasks to run while waiting for I/O operations to finish, thus potentially improving overall concurrency and responsiveness of your application. </p>
<p>It's important to note that asyncio doesn't eliminate the GIL itself – rather, it provides an alternative concurrency model that can be more efficient for certain types of applications. </p>
<p>For <strong>CPU-bound tasks</strong>, asyncio may not provide the same performance benefits as multiprocessing or other parallelism techniques, as it still operates within the constraints of the GIL. In such cases, multiprocessing or other concurrency approaches may be more suitable.</p>
<h2 id="heading-summary">Summary</h2>
<p>In this article, you learned about the differences between Multi-threading, Multi-processing, Asynchronous Programming, and Concurrency. Let's review them briefly now:</p>
<h3 id="heading-multi-threading">Multi-threading:</h3>
<ul>
<li>Definition<em>:</em> Multi-threading involves using multiple threads to execute tasks <strong>concurrently</strong> within a single process. Concurrently is nothing but the concept Concurrency here.</li>
<li>Clarification<em>:</em> Threads share the same memory space, allowing them to communicate easily but requiring careful synchronization to avoid conflicts.</li>
</ul>
<h3 id="heading-multi-processing">Multi-processing:</h3>
<ul>
<li>Definition<em>:</em> Multi-processing involves using multiple processes to run your application or tasks. Each <strong>process</strong> has its own memory space and resources.</li>
<li>Clarification<em>:</em> Processes are independent, and communication between them often requires inter-process communication (IPC) mechanisms. Each process operates in its own memory space.</li>
</ul>
<h3 id="heading-asynchronous-programming">Asynchronous Programming:</h3>
<ul>
<li>Definition<em>:</em> Asynchronous programming is a programming concept that allows tasks to be executed separately from the main program flow. It doesn't necessarily imply concurrent execution.</li>
<li>Clarification<em>:</em> Asynchronous tasks don't block the main program, enabling the program to continue its execution while waiting for the asynchronous tasks to complete. This is commonly used in I/O operations to improve efficiency.</li>
</ul>
<h3 id="heading-concurrency">Concurrency:</h3>
<ul>
<li>Definition<em>:</em> Concurrency is a broader concept that refers to the ability of a system to execute multiple tasks in overlapping time intervals, that is switching between the tasks in specific intervals.</li>
<li>Clarification<em>:</em> Concurrency doesn't guarantee simultaneous execution but rather focuses on efficiently managing multiple tasks by switching between them. It encompasses multi-threading, multi-processing, and asynchronous programming as ways to achieve concurrent execution.</li>
</ul>
<p>I hope you now have a clear understanding of the concepts that may have seemed scary before. I understand it's mostly theoretical, but I want to ensure you grasp the concept well before diving into the practical aspect.</p>
<p>Until then, your friend here, Hemachandra, is signing off…</p>
<p>For more courses, you can visit my personal <a target="_blank" href="https://datatechs.in/">website</a>.</p>
<p><em>Have a great day!</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Databases Guarantee Isolation – Pessimistic vs Optimistic Concurrency Control Explained ]]>
                </title>
                <description>
                    <![CDATA[ ACID (Atomicity, Consistency, Isolation, and Durability) is a set of guarantees when working with a DBMS. Pessimistic and optimistic concurrency control explains how databases achieve the “I” in ACID. Isolation is a guarantee that concurrently runnin... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-databases-guarantee-isolation/</link>
                <guid isPermaLink="false">66d45e12f855545810e93431</guid>
                
                    <category>
                        <![CDATA[ concurrency ]]>
                    </category>
                
                    <category>
                        <![CDATA[ database ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Daniel Adetunji ]]>
                </dc:creator>
                <pubDate>Mon, 05 Feb 2024 22:41:18 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/cover--1-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>ACID (Atomicity, Consistency, Isolation, and Durability) is a set of guarantees when working with a DBMS. Pessimistic and optimistic concurrency control explains how databases achieve the “I” in ACID.</p>
<p>Isolation is a guarantee that concurrently running transactions should not interfere with each other. This is arguably the most important ACID property, because different DBMS can often have different default isolation levels. And you may need to change this based on what is needed for your application.</p>
<p>In a <a target="_blank" href="https://lightcloud.substack.com/p/acid-databases-explained">previous article</a>, I explained the two main isolation levels used by most DBMS. These are the <a target="_blank" href="https://lightcloud.substack.com/i/140524854/read-committed">read committed</a> and <a target="_blank" href="https://lightcloud.substack.com/i/140524854/repeatable-read">repeatable read</a> isolation levels.</p>
<p>Pessimistic and optimistic concurrency controls essentially explain some of the ways a database is able to achieve these two isolation guarantees.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-pessimistic-concurrency-control">Pessimistic Concurrency Control</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-a-library-analogy-for-pessimistic-concurrency-control">Pessimistic Concurrency Control Analogy</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-a-simple-real-world-example-of-pessimistic-concurrency-control-in-action">Real-World Example of Pessimistic Concurrency Control</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-benefits-and-challenges-of-pessimistic-concurrency-control">Pros and Cons of Pessimistic Concurrency Control</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-pessimistic-concurrency-controls-guarantee-the-read-committed-isolation-level">How it Guarantees the Read Committed Isolation Level</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-optimistic-concurrency-control">Optimistic Concurrency Control</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-a-simple-real-world-example-of-optimistic-concurrency-control-in-action">Real-World Example of Optimistic Concurrency Control</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-benefits-and-challenges-of-optimistic-concurrency-control">Pros and Cons of Optimistic Concurrency Control</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-optimistic-concurrency-controls-guarantee-the-repeatable-read-isolation-level">How it Guarantees the Repeatable Read Isolation Level</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-bringing-it-together">Bringing it Together</a></p>
</li>
</ol>
<h2 id="heading-pessimistic-concurrency-control">Pessimistic Concurrency Control</h2>
<p>With pessimistic concurrency control, the DBMS assumes that conflicts between transactions are likely to occur. It is pessimistic – that is, it assumes that if something can go wrong, it will go wrong. This pessimism prevents conflicts from occurring by blocking them before they get a chance to start.</p>
<p>To prevent these conflicts, it <em>locks</em> the data that a transaction is using until the transaction is completed. This approach is 'pessimistic' because it assumes the worst-case scenario – that every transaction might lead to a <em>conflict</em>. The data is therefore locked in order to prevent conflicts from happening.</p>
<p>I've mentioned two technical terms here that need clarification: <em>locks</em> and <em>conflict</em>.</p>
<h3 id="heading-what-are-locks">What are locks?</h3>
<p>A lock is a mechanism used to control access to a database item, like a row or table. Locks ensure data integrity, if multiple transactions are occurring at the same time.</p>
<p>In very simple terms, a lock is analogous to a reservation on the database item. A reservation, be it a restaurant, hotel, or a train, prevents other people from using the resource you reserved for a fixed duration of time. Locks work in a similar way.</p>
<p>There are two types of locks: a read lock and a write lock.</p>
<p>A read lock can be shared by multiple transactions trying to read the same database item. But it blocks other transactions from updating that database item.</p>
<p>A write lock is exclusive – that is, it can only be held by a single transaction. A transaction with a write lock on a database item blocks every other transaction from reading or updating that database item.</p>
<h3 id="heading-what-are-conflicts">What are conflicts?</h3>
<p>A conflict refers to a situation where multiple transactions are attempting to access and modify the same data concurrently, in a way that could lead to inconsistencies or errors in the database.</p>
<h3 id="heading-a-library-analogy-for-pessimistic-concurrency-control">A Library Analogy for Pessimistic Concurrency Control</h3>
<p>First, let us describe an analogy for a write lock.</p>
<p>Imagine you're at a library, and you want to borrow a hard copy of a popular book, say, The Great Gatsby by F. Scott Fitzgerald.</p>
<p><img src="https://substackcdn.com/image/fetch/w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcd683922-af28-4886-a6dc-6c121ac7e915_1858x1054.png" alt="Image" width="1456" height="826" loading="lazy"></p>
<p><em>Write locks are analogous to borrowing a physical book from the library</em></p>
<p>With a write lock, the librarian assumes that there can be conflicts over who gets to borrow the book. So, they implement a strict rule to avoid conflicts: only one person can hold the reservation for a physical book at a time.</p>
<p>When you reserve the book, no one else can borrow it. The book is available to be reserved again only once it is returned. This is similar to how a write lock works.</p>
<p>Write locks are exclusive. This means that they can only he held by a single transaction at any time. Similarly, reserving a physical book from the library means no one else has access to it. Only the person with the reservation can read the book, or write in it (although writing in a library book is bad form).</p>
<p>Read locks work a bit differently.</p>
<p>A read lock is analogous to someone making a reservation to borrow an e-book. Borrowing an e-book is not a very popular thing to do, but some libraries do have such a service.</p>
<p>Many people can make the same reservation for the same e-book without any conflict. One person borrowing an e-book version of The Great Gatsby does not stop others from doing the same. But no one who borrows an e-book can update it, by scribbling notes in it that can be seen by others, for example.</p>
<p><img src="https://substackcdn.com/image/fetch/w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbb2c7acc-c32e-47f6-a412-2000ae14da2b_2156x1344.png" alt="Image" width="1456" height="908" loading="lazy"></p>
<p><em>Read locks are analogous to borrowing an e-book from the library</em></p>
<p>Pessimistic concurrency control is very safe because it prevents conflicts from occurring by blocking them before they get a chance to start. A write lock on a database item prevents other transactions from reading or updating that item while that lock is held, similar to to how a library stops more than one person from trying to borrow the same physical book at the same time.</p>
<p>A read lock on a database item allows other transactions to also obtain a read lock for that item, but prevents transactions from updating that item. This is analogous to borrowing an e-book, where multiple people can borrow the same e-book at the same time, but can’t make any updates to it.</p>
<h3 id="heading-a-simple-real-world-example-of-pessimistic-concurrency-control-in-action">A Simple Real-World Example of Pessimistic Concurrency Control in Action</h3>
<p>Let's illustrate how pessimistic concurrency control works using a simple example involving a bank balance database table. Assume we have a table named Accounts with the following columns: AccountID and Balance.</p>
<p><img src="https://substackcdn.com/image/fetch/w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1d9e2dd5-5abe-46ea-bbb6-033f1d5bc663_1096x534.png" alt="Image" width="1096" height="534" loading="lazy"></p>
<p><em>Database columns for AccountID and Balance</em></p>
<p>Two transactions, T1 and T2, intend to update the balance of account 12345. T1 wants to withdraw $300, and T2 wants to deposit $400. At the end of these two transactions, the account balance should read $1600</p>
<p>Here are the steps of how this will work using write locks:</p>
<ol>
<li><p>Start of T1 (Withdrawal): T1 requests to update the balance of AccountID 12345. The database system places an exclusive write lock on the row for AccountID 12345, preventing other transactions from reading or writing to this row until T1 is completed. T1 reads the balance ($1500).</p>
</li>
<li><p>T1 Processing: T1 calculates the new balance as $1200 ($1500 - $300).</p>
</li>
<li><p>Commit T1: T1 writes the new balance ($1200) back to the database. Upon successful commit, T1 releases the exclusive lock on AccountID 12345.</p>
</li>
<li><p>Start of T2 (Deposit) After T1 Completes: Now that T1 has completed and the lock is released, T2 can start. T2 attempts to read and update the balance for AccountID 12345. The database system places an exclusive lock on the row for AccountID 12345 for T2, ensuring no other transactions can interfere. T2 reads the updated balance ($1200).</p>
</li>
<li><p>T2 Processing: T2 calculates the new balance as $1600 ($1200 + $400).</p>
</li>
<li><p>Commit T2: T2 writes the new balance ($1600) back to the database. Upon successful commit, T2 releases the exclusive lock on AccountID 12345.</p>
</li>
<li><p>Result: The Accounts table is updated using locks After T1: $1200 After T2: $1600</p>
</li>
</ol>
<p>Without a write lock in this example, T1 and T2 could read the original balance of $1500 at the same time. So, instead of a balance of $1200 after T1 has committed, T2 still reads the original balance of $1500 and adds $400. This would cause the final balance to be $1500 + $400 = $1900 (instead of $1600).</p>
<p>Absence of locking has created free money, which is never a bad thing for a customer. But, if money can be conjured out of thin air because of these conflicts, it can also vanish, and accidentally shrinking bank balances are a quick way to make customers unhappy.</p>
<h3 id="heading-benefits-and-challenges-of-pessimistic-concurrency-control">Benefits and Challenges of Pessimistic Concurrency Control</h3>
<p>Just like reserving a book ensures that it's set aside for one person, pessimistic concurrency control locks data for a single transaction. Other transactions cannot access or modify this data until the lock is released.</p>
<p>This method prevents two people from trying to take out the same popular book at the same time, thereby avoiding disputes. Similarly, in databases, it stops conflicts due to concurrent transactions before they get a chance to start.</p>
<p>But this approach can be inefficient. The reserved book might sit on the reserved shelf for a while, stopping other people from reading it.</p>
<p>In databases, this locking mechanism can lead to underutilisation of resources and a slowdown in the speed transactions take to complete, since a subset of the data is locked and inaccessible to other transactions.</p>
<h3 id="heading-how-pessimistic-concurrency-controls-guarantee-the-read-committed-isolation-level">How Pessimistic Concurrency Controls Guarantee the Read Committed Isolation Level</h3>
<p>So, how exactly does pessimistic concurrency control work in ensuring the isolation guarantee, that is the “I” in ACID? The implementation details can vary across different DBMS. But the explanation here shows the general approach.</p>
<p>Recall that <a target="_blank" href="https://lightcloud.substack.com/i/140524854/read-committed">the read committed isolation</a> level prevents dirty writes and dirty reads.</p>
<h4 id="heading-preventing-dirty-writes">Preventing Dirty Writes</h4>
<p>Overwriting data that has already been written by another transaction but not yet committed is called a dirty write. A common approach to preventing dirty writes is to use pessimistic concurrency control. For example, by using a write lock at the row level.</p>
<p>When a transaction wants to modify a row, it acquires a lock on that row and holds it until the transaction is complete. Recall that write locks can only be held by a single transaction. This prevents another transaction from acquiring a lock to modify that row.</p>
<h4 id="heading-preventing-dirty-reads">Preventing Dirty Reads</h4>
<p>Reading data from another transaction that has not yet been committed is called a dirty read. Dirty reads are prevented using either a read or write lock. Once a transaction acquires a read lock on a database item, it will prevent updates to that item.</p>
<p>But what happens if you are trying to read something that is already being updated but the transaction has not yet committed? In this instance, the write lock saves the day again.</p>
<p>Since write locks are exclusive (can’t be shared with other transactions), any transaction wanting to read the same database item will have to wait until the transaction with the write lock is committed (or aborted, if it fails). This prevents other transactions from reading uncommitted changes.</p>
<h2 id="heading-optimistic-concurrency-control">Optimistic Concurrency Control</h2>
<p>With optimistic concurrency control, transactions do not obtain locks on data when they read or write. The "Optimistic" in the name comes from assuming that conflicts are unlikely to occur, so locks are not needed. If something does go wrong though, conflicts will still be prevented and everything will be OK.</p>
<p>Unlike pessimistic concurrency control – which prevents conflicts from occurring by blocking them before they get a chance to start – optimistic concurrency control checks for conflicts at the end of a transaction.</p>
<p>With optimistic concurrency control, multiple transactions can read or update the same database item without acquiring locks. How exactly does this work?</p>
<p>Every time a transaction wants to update a database item, say a row, it will also read two additional columns added to every table by the DBMS – the timestamp and the version number. Before that transaction is committed, it checks if another transaction has made any change(s) to that row by confirming if the version number and timestamp are the same.</p>
<p>If they have changed, that means another transaction has updated that row, so the initial transaction will have to be retried.</p>
<h3 id="heading-a-simple-real-world-example-of-optimistic-concurrency-control-in-action">A Simple Real-World Example of Optimistic Concurrency Control in Action</h3>
<p>Let's illustrate how optimistic concurrency control works using a simple example involving a bank balance database table. Assume we have a table named Accounts with the following columns: AccountID, Balance, VersionNumber, and Timestamp.</p>
<p><img src="https://substackcdn.com/image/fetch/w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc46a7d00-c1b9-46c6-80c0-0bc1a7aba9ae_2180x542.png" alt="Image" width="1456" height="362" loading="lazy"></p>
<p><em>Table showing AccountID, Balance, VersionNumber, and Timestamp columns</em></p>
<p>Two transactions, T1 and T2, intend to update the balance of account 12345 at the same time. T1 wants to withdraw $200, and T2 wants to deposit $300. At the end of these two transactions, the account balance should read $1100</p>
<p>Here are the steps of how this will work:</p>
<ol>
<li><p>Start of Transactions: T1 reads the balance, version number, and timestamp for AccountID 12345. Simultaneously, T2 reads the same row with the same balance, version number, and timestamp.</p>
</li>
<li><p>Processing: T1 calculates the new balance as $800 ($1000 - $200) but does not write it back immediately. T2 calculates the new balance as $1300 ($1000 + $300) but also waits to commit.</p>
</li>
<li><p>Attempt to Commit T1: Before committing, T1 checks the current VersionNumber and Timestamp of AccountID 12345 in the database. Since no other transaction has modified the row, T1 updates the balance to $800, increments the VersionNumber to 2, updates the Timestamp, and commits successfully.</p>
</li>
<li><p>Attempt to Commit T2: T2 attempts to commit by first verifying the VersionNumber and Timestamp. T2 finds that the VersionNumber and Timestamp have changed (now VersionNumber is 2, and Timestamp is updated), indicating another transaction (T1) has updated the row. Since the version number and timestamp have changed, T2 realises there was a conflict.</p>
</li>
<li><p>Resolution for T2: T2 must restart its transaction. It re-reads the updated balance of $800, the new VersionNumber 2, and the updated Timestamp. T2 recalculates the new balance as $1100 ($800 + $300), updates the VersionNumber to 3, updates the Timestamp, and commits successfully.</p>
</li>
</ol>
<p>Result: The Accounts table is updated sequentially and safely without any locks: After T1: $800, VersionNumber: 2. After T2: $1100, VersionNumber: 3.</p>
<h3 id="heading-benefits-and-challenges-of-optimistic-concurrency-control">Benefits and Challenges of Optimistic Concurrency Control</h3>
<p>On the positive side, avoiding locks allows for high levels of concurrency. This is particularly beneficial in read-heavy workloads where transactions are less likely to conflict, allowing the system to handle more transactions in a given period. For example, database backups and analytical queries typically used in a data warehouse.</p>
<p>But in scenarios where conflicts are frequent, the cost of repeatedly rolling back and retrying transactions can outweigh the benefits of avoiding locks, making optimistic concurrency control less efficient</p>
<h3 id="heading-how-optimistic-concurrency-controls-guarantee-the-repeatable-read-isolation-level">How Optimistic Concurrency Controls Guarantee the Repeatable Read Isolation level</h3>
<p>The repeatable read is more strict isolation level in that it has the same guarantees as read committed isolation, plus it guarantees that reads are repeatable.</p>
<p>A repeatable read guarantees that if a transaction reads a row of data, any subsequent reads of that same row of data within the same transaction will yield the same result, regardless of changes made by other transactions. This consistency is maintained throughout the duration of the transaction.</p>
<p>How can a repeatable read be achieved? Pessimistic control using a read lock can help with this, since a transaction with a read lock on a database item will prevent that item from being updated. But this can be inefficient, since a long running read transaction can block updates from happening to that database item.</p>
<p>Multi-Version Concurrency Control (MVCC) is a concurrency control method used by some DBMS to allow multiple transactions to access the same data simultaneously without locking the data. This makes it a popular choice for reducing lock contention and improving the scalability of databases.</p>
<p>MVCC achieves this by keeping multiple versions of data objects, which helps to manage different visibility levels for transactions depending on their timestamps or version numbers.</p>
<h2 id="heading-bringing-it-together">Bringing it Together</h2>
<p>A lock is a mechanism used to control access to a database item, like a row or table. In very simple terms, it is analogous to a reservation on a database item.</p>
<p>Pessimistic concurrency control assumes the worst. It assumes that conflicts are likely to happen, so locks are used to block transactions that can cause conflicts before they even get a chance to start.</p>
<p>In situations where conflicts are common, such as a write heavy application, this approach can prevent the overhead associated with frequent rollbacks and retries (which happens in optimistic concurrency control) by ensuring exclusive access to database items during transactions.</p>
<p>Optimistic concurrency control assumes the best. It assumes that conflicts are unlikely to occur, so locks are not needed to stop transactions before they start. Instead, potential conflicts are checked at the end of a transaction and if any are found, the transaction is aborted or retried.</p>
<p>Optimistic concurrency control is useful for read heavy transactions with infrequent writes, as it allows multiple transactions to proceed without the need to use a lock, which can be inefficient.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Atomics and Concurrency in C++ ]]>
                </title>
                <description>
                    <![CDATA[ By Zaid Humayun Concurrency is a programming term you'll need to be familiar with if you code in C++. It's especially relevant if you want to get more out of your available compute resources.  But concurrency comes with certain problems. Some of them... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/atomics-and-concurrency-in-cpp/</link>
                <guid isPermaLink="false">66d461c7787a2a3b05af4425</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ concurrency ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 16 Jan 2024 23:50:05 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/pexels-pixabay-290470.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Zaid Humayun</p>
<p>Concurrency is a programming term you'll need to be familiar with if you code in C++. It's especially relevant if you want to get more out of your available compute resources. </p>
<p>But concurrency comes with certain problems. Some of them can be solved using <a target="_blank" href="https://en.wikipedia.org/wiki/Mutual_exclusion">mutexes</a>, although mutexes have their own set of <a target="_blank" href="https://stackoverflow.com/questions/74521674/why-mutex-lock-on-c-affects-multithreading-efficiency-so-badly">challenges</a>.</p>
<p>This is where <a target="_blank" href="https://stackoverflow.com/questions/52196678/what-are-atomic-operations-for-newbies">atomics</a> come in. However, atomics require an understanding of the memory model of a computer, which is a challenging topic to fully grasp.</p>
<p>This is what we'll cover in this article. Hopefully you'll gain a good understanding of how memory ordering works and how to use atomics in conjunction with memory ordering to build a lock-free queue in C++.</p>
<h2 id="heading-pre-requisites">Pre-requisites</h2>
<p>To get the most out of this guide, you need to have written some basic concurrent programs. Programming experience with C++ helps.</p>
<p>Note: If you want to actually compile the code and run it, make sure to do so with the TSan flag enabled for the CLang compiler. TSan is a reliable way of detecting data races in your code, instead of trying to repeatedly run the code in a loop hoping for a data race to occur.</p>
<h2 id="heading-getting-started">Getting Started</h2>
<p>Imagine you have some concurrent code operating on some shared data in memory. You have two threads or processes, one writing and one reading on some shared piece of state.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/processes-shared-memory.jpeg" alt="Image" width="600" height="400" loading="lazy">
<em>Processes sharing memory</em></p>
<p>The "safe" way of dealing with this is mutexes. But mutexes tend to add overhead. Atomics are a more performant but much more complicated way of dealing with concurrent operations.</p>
<h2 id="heading-what-are-atomics-in-c">What Are Atomics in C++?</h2>
<p>This section is very simple. Atomics are simply operations or instructions that cannot be split by the compiler or the CPU or re-ordered in any way.</p>
<p>The simplest possible example of an atomic in C++ is an atomic flag. It looks like this:</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;atomic&gt;</span></span>

<span class="hljs-function"><span class="hljs-built_in">std</span>::atomic&lt;<span class="hljs-keyword">bool</span>&gt; <span class="hljs-title">flag</span><span class="hljs-params">(<span class="hljs-literal">false</span>)</span></span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
  flag.store(<span class="hljs-literal">true</span>);
  assert(flag.load() == <span class="hljs-literal">true</span>);
}
</code></pre>
<p>We define an atomic boolean, initialise it, and then call <code>store</code> on it. This method sets the value on the flag. You can then <code>load</code> the flag from memory and assert its value.</p>
<h3 id="heading-operations-with-atomics">Operations with Atomics</h3>
<p>The operations you can perform with atomics are straightforward:</p>
<ol>
<li>You can store some value into them with the <code>store()</code> method. This is a write operation.</li>
<li>You can load some value from them with the <code>load()</code> method. This is a read operation.</li>
<li>You can do a Compare-and-Set (CAS) with them using the <code>compare_exchange_weak()</code> or <code>compare_exchange_strong()</code> method. This is a read-modify-write (RMW) operation.</li>
</ol>
<p>The important thing to remember is that each of these cannot be split into separate instructions.</p>
<p>Note: There are more methods available, but this is all we need for now.</p>
<p>There are various atomics available in C++ and you can use them in combination with memory orderings.</p>
<h2 id="heading-memory-ordering">Memory Ordering</h2>
<p>This section is a lot more complicated and is the meat of the matter. There are some great references to help you understand memory ordering in more depth that I've linked at the bottom.</p>
<h3 id="heading-why-memory-ordering-matters">Why Memory Ordering Matters</h3>
<p>The compiler and CPU are capable of re-ordering your program instructions, often independently of one another. That is, your compiler can re-order instructions and your CPU can re-order instructions again. See <a target="_blank" href="https://www.reddit.com/r/cpp/comments/dh3hle/why_is_compiler_allowed_to_reorder_instructions/">this post</a> for more detail.</p>
<p>But this is only allowed if the compiler can definitely <em>not</em> establish a relationship between the two sets of instructions.</p>
<p>For instance, the below code can be re-ordered because there is no relationship between the assignment to x and the assignment to y. That is, the compiler or CPU might assign y first and then x. But, this doesn't change the semantic meaning of your program.</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">int</span> x = <span class="hljs-number">10</span>;
<span class="hljs-keyword">int</span> y = <span class="hljs-number">5</span>;
</code></pre>
<p>On the other hand, the following code example cannot be re-ordered because the compiler cannot establish the absence of a relationship between x and y. It's pretty easy to see here because y depends on the value of x.</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">int</span> x = <span class="hljs-number">10</span>;
<span class="hljs-keyword">int</span> y = x + <span class="hljs-number">1</span>;
</code></pre>
<p>This doesn't seem like a big problem – until there's multi-threaded code. Let's see what I mean with an example.</p>
<h3 id="heading-intuition-for-ordering">Intuition for Ordering</h3>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;cassert&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;thread&gt;</span></span>

<span class="hljs-keyword">int</span> data = <span class="hljs-number">0</span>;

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">producer</span><span class="hljs-params">()</span> </span>{
  data = <span class="hljs-number">100</span>;  <span class="hljs-comment">// Write data</span>
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">consumer</span><span class="hljs-params">()</span> </span>{
  assert(data == <span class="hljs-number">100</span>);
}

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-function"><span class="hljs-built_in">std</span>::thread <span class="hljs-title">t1</span><span class="hljs-params">(producer)</span></span>;
  <span class="hljs-function"><span class="hljs-built_in">std</span>::thread <span class="hljs-title">t2</span><span class="hljs-params">(consumer)</span></span>;
  t1.join();
  t2.join();
  <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>The multi-threaded example above will fail to compile with TSan because there is a clear data race when thread 1 is trying to set the value of data and thread 2 is trying to read the value of data. The easy answer here is a mutex to protect the write and read of data, but there's a way to do this with an atomic boolean.</p>
<p>We loop on the atomic boolean until we find that it is set to the value we are looking for and then check the the value of <code>data</code>.</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;atomic&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;cassert&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;thread&gt;</span></span>

<span class="hljs-keyword">int</span> data = <span class="hljs-number">0</span>;
<span class="hljs-function"><span class="hljs-built_in">std</span>::atomic&lt;<span class="hljs-keyword">bool</span>&gt; <span class="hljs-title">ready</span><span class="hljs-params">(<span class="hljs-literal">false</span>)</span></span>;

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">producer</span><span class="hljs-params">()</span> </span>{
  data = <span class="hljs-number">100</span>;
  ready.store(<span class="hljs-literal">true</span>);  <span class="hljs-comment">// Set flag</span>
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">consumer</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-keyword">while</span> (!ready.load())
    ;
  assert(data == <span class="hljs-number">100</span>);
}

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-function"><span class="hljs-built_in">std</span>::thread <span class="hljs-title">t1</span><span class="hljs-params">(producer)</span></span>;
  <span class="hljs-function"><span class="hljs-built_in">std</span>::thread <span class="hljs-title">t2</span><span class="hljs-params">(consumer)</span></span>;
  t1.join();
  t2.join();
  <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>When you compile this with TSan, it doesn't complain about any race conditions. Note: I'm going to refer back to why TSan doesn't complain here a little further on.</p>
<p>Now, I'm going to break it by adding a memory ordering guarantee to it. Just replace <code>ready.store(true);</code> with <code>ready.store(true, std::memory_order_relaxed);</code> and replace <code>while (!ready.load())</code> with <code>while (!ready.load(std::memory_order_relaxed))</code>.</p>
<p>TSan will complain that there is a data race. But, why is it complaining?</p>
<p>The issue here is that we have no order among the operations of the two threads anymore. The compiler or CPU is free to re-order instructions in the two threads. If we go back to our abstract visualisation from earlier, this is what it looks like now:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/memory-relaxed.jpeg" alt="Image" width="600" height="400" loading="lazy">
<em>Relaxed memory model ordering</em></p>
<p>The visualisation above shows us that our two processes (threads) have no way of agreeing upon the current state or the order in which that state has changed.</p>
<p>Once process 2 determines that the flag has been set to true, so it tries to read the value of <code>data</code>. But, thread 2 believes that the value of <code>data</code> has not yet changed even though it believes the value of <code>flag</code> has been set to true.</p>
<p>This is confusing because the classic model of interleaving concurrent operations doesn't apply here. In the classic model of concurrent operations, there is always some order that can be established. For instance, we can say that this is one possible scenario of operations:</p>
<pre><code>Thread <span class="hljs-number">1</span>                  Memory                  Thread <span class="hljs-number">2</span>
---------                 -------                 ---------
  |                          |                          |
  |   write(data, <span class="hljs-number">100</span>)       |                          |
  | -----------------------&gt; |                          |
  |                          |     load(ready) == <span class="hljs-literal">true</span>  |
  |                          | &lt;----------------------  |
  |                          |                          |
  |   store(ready, true)     |                          |
  | -----------------------&gt; |                          |
  |                          |                          |
  |                          |       read(data)         |
  |                          | &lt;----------------------  |
  |                          |                          |
</code></pre><p>But, the above graphic <em>assumes</em> that both threads have agreed upon some global order of events, which isn't true at all anymore! This is still confusing for me to wrap my head around.</p>
<p>In a <code>memory_order_relaxed</code> mode, two threads have no way of agreeing upon the order of operations on shared variables. From thread 1's point of view, the operations it executed were the following:</p>
<pre><code>write(data, <span class="hljs-number">100</span>)
store(ready, <span class="hljs-literal">true</span>)
</code></pre><p>However, from thread 2's point of view, the order of operations <em>it saw</em> thread 1 execute were:</p>
<pre><code>store(ready, <span class="hljs-literal">true</span>)
write(data, <span class="hljs-number">100</span>)
</code></pre><p>Without agreeing upon the order in which operations occurred on <em>shared variables</em>, it isn't safe to make changes to those variables across threads.</p>
<p>Okay, let's fix the code by replacing <code>std::memory_order_relax</code> with <code>std::memory_order_seq_cst</code>.</p>
<p>So, <code>ready.store(true, std::memory_order_relaxed);</code> becomes <code>ready.store(true, std::memory_order_seq_cst);</code> and <code>while (!ready.load(std::memory_order_relaxed))</code> becomes <code>while (!ready.load(std::memory_order_seq_cst))</code>.</p>
<p>If you run this again with TSan, there are no more data races. But why did that fix it?</p>
<h3 id="heading-memory-barrier">Memory Barrier</h3>
<p>So, we saw our problem earlier was about two threads being unable to agree upon a single view of events and we wanted to prevent that. So, we introduced a <em>barrier</em> using sequential consistency.</p>
<pre><code>Thread <span class="hljs-number">1</span>                  Memory                  Thread <span class="hljs-number">2</span>
---------                 -------                 ---------
  |                          |                          |
  |   write(data, <span class="hljs-number">100</span>)       |                          |
  | -----------------------&gt; |                          |
  |                          |                          |
  |  ================Memory Barrier===================  |
  |   store(ready, <span class="hljs-literal">true</span>)     |                          |
  | -----------------------&gt; |                          |
  |                          |   load(ready) == <span class="hljs-literal">true</span>    |                   
  |                          | &lt;----------------------  |
  |  ================Memory Barrier===================  |
  |                          |                          |
  |                          |       read(data)         |
  |                          | &lt;----------------------  |
  |                          |                          |
</code></pre><p>The memory barrier here says that nothing before the store operation and nothing after the load operation can be re-ordered. That is, thread 2 now has a guarantee that the compiler or the CPU will not place the write to data after the write to the flag in thread 1. Similarly, the read operation in thread 2 cannot be re-ordered above the memory barrier.</p>
<p>The region inside the memory barrier is akin to a critical section that a thread needs to a mutex to enter. We now have a way to synchronise the two threads on the order of events across them.</p>
<p>This brings us back to our classic model of interleaving in concurrency because we now have an order of events both threads agree upon.</p>
<h3 id="heading-types-of-memory-order">Types Of Memory Order</h3>
<p>There are 3 main types of memory order:</p>
<ol>
<li>Relaxed memory model (std::memory_order_relaxed)</li>
<li>Release-acquire memory model (std::memory_order_release and std::memory_order_acquire)</li>
<li>Sequentially consistent memory order (std::memory_order_seq_cst)</li>
</ol>
<p>We already covered 1 and 3 in the examples above. The second memory model literally lies between the other two in terms of consistency.</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;atomic&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;cassert&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;thread&gt;</span></span>

<span class="hljs-keyword">int</span> data = <span class="hljs-number">0</span>;
<span class="hljs-function"><span class="hljs-built_in">std</span>::atomic&lt;<span class="hljs-keyword">bool</span>&gt; <span class="hljs-title">ready</span><span class="hljs-params">(<span class="hljs-literal">false</span>)</span></span>;

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">producer</span><span class="hljs-params">()</span> </span>{
  data = <span class="hljs-number">100</span>;
  ready.store(<span class="hljs-literal">true</span>, <span class="hljs-built_in">std</span>::memory_order_release);  <span class="hljs-comment">// Set flag</span>
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">consumer</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-keyword">while</span> (!ready.load(<span class="hljs-built_in">std</span>::memory_order_acquire))
    ;
  assert(data == <span class="hljs-number">100</span>);
}

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-function"><span class="hljs-built_in">std</span>::thread <span class="hljs-title">t1</span><span class="hljs-params">(producer)</span></span>;
  <span class="hljs-function"><span class="hljs-built_in">std</span>::thread <span class="hljs-title">t2</span><span class="hljs-params">(consumer)</span></span>;
  t1.join();
  t2.join();
  <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>The above is the same example from earlier, expect with <code>std::memory_order_release</code> used for <code>ready.store()</code> and <code>memory_order_acquire</code> used for <code>read.load()</code>. The intuition here for ordering is similar to the pervious memory barrier example.</p>
<p>Except, this time the memory barrier is formed on the pair of <code>ready.store()</code> and <code>ready.load()</code> operations and will only work when used on the <em>same</em> atomic variable across threads. </p>
<p>Assuming you have a variable <code>x</code> being modified across 2 threads, you could do <code>x.store(std::memory_order_release)</code> in thread 1 and <code>x.load(std::memory_order_acquire)</code> in thread 2 and you would have a synchronization point across the two threads on this variable.</p>
<p>The difference between the sequentially consistent model and the release-acquire model is that the former enforces a global order of operations across all threads, while the latter enforces an order only among pairs of release and acquire operations.</p>
<p>Now, we can revisit why TSan didn't complain about a data race initially when there was no memory order specified. It's because C++ by default assumes a <code>std::memory_order_seq_cst</code> when no memory order is specified. Since this is the strongest memory mode, there is no data race possible.</p>
<h2 id="heading-hardware-considerations">Hardware Considerations</h2>
<p>Different memory models have different performance penalties on different hardware.</p>
<p>For instance, the x86 architectures instruction set implements something called total store ordering (TSO). The gist of it is that the model resembles all threads reading and writing to a shared memory. You can read more about that <a target="_blank" href="https://research.swtch.com/hwmm#:~:text=x86%20Total%20Store%20Order%20(x86,in%20a%20local%20write%20queue.)">here</a>.</p>
<p>This means that the x86 processors can provide sequential consistency for a relatively low computational penalty.</p>
<p>On the other side are the ARM family of processors has a weakly ordered instruction set architecture. This is because each thread or process reads and writes to its own memory. Again, the link above provides context.</p>
<p>This means that the ARM processors provide sequential consistency for a much higher computational penalty.</p>
<h2 id="heading-how-to-build-a-concurrent-queue">How to Build a Concurrent Queue</h2>
<p>I'm going to use the operations we have discussed so far to build the basic operations of a lock-free concurrent queue. This is by no means even a complete implementation, just my attempt to re-create something basic using atomics.</p>
<p>I'm going to represent the queue using a linked list and wrap each node inside an atomic.</p>
<pre><code class="lang-cpp"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">lock_free_queue</span> {</span>
 <span class="hljs-keyword">private</span>:
  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">node</span> {</span>
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">shared_ptr</span>&lt;T&gt; data;
    <span class="hljs-built_in">std</span>::atomic&lt;node*&gt; next;

    node() : next(<span class="hljs-literal">nullptr</span>) {}  <span class="hljs-comment">//  initialise the node</span>
  };

  <span class="hljs-built_in">std</span>::atomic&lt;node*&gt; head;
  <span class="hljs-built_in">std</span>::atomic&lt;node*&gt; tail;
}
</code></pre>
<p>Now, for the enqueue operation, this is what it's going to look like:</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">enqueue</span><span class="hljs-params">(T value)</span> </span>{
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">shared_ptr</span>&lt;T&gt; new_data = <span class="hljs-built_in">std</span>::make_shared&lt;T&gt;(value);
    node* new_node = <span class="hljs-keyword">new</span> node();
    new_node-&gt;data = new_data;

    <span class="hljs-comment">//  do an infinite loop to change the tail</span>
    <span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>) {
      node* current_tail = <span class="hljs-keyword">this</span>-&gt;tail.load(<span class="hljs-built_in">std</span>::memory_order_acquire);
      node* tail_next = current_tail-&gt;next;

      <span class="hljs-comment">//  everything is correct so far, attempt the swap</span>
      <span class="hljs-keyword">if</span> (current_tail-&gt;next.compare_exchange_strong(
              tail_next, new_node, <span class="hljs-built_in">std</span>::memory_order_release)) {
        <span class="hljs-keyword">this</span>-&gt;tail = new_node;
        <span class="hljs-keyword">break</span>;
      }
    }
  }
</code></pre>
<p>The main focus is on the <code>load</code> and <code>compare_exchange_strong</code> operations. The <code>load</code> works with an <code>acquire</code> and the CAS works with a <code>release</code> so that reads and writes to the tail are synchronized.</p>
<p>Similarly for the dequeue operation:</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-built_in">std</span>::<span class="hljs-built_in">shared_ptr</span>&lt;T&gt; <span class="hljs-title">dequeue</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">shared_ptr</span>&lt;T&gt; return_value = <span class="hljs-literal">nullptr</span>;

    <span class="hljs-comment">//  do an infinite loop to change the head</span>
    <span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>) {
      node* current_head = <span class="hljs-keyword">this</span>-&gt;head.load(<span class="hljs-built_in">std</span>::memory_order_acquire);
      node* next_node = current_head-&gt;next;

      <span class="hljs-keyword">if</span> (<span class="hljs-keyword">this</span>-&gt;head.compare_exchange_strong(current_head, next_node,
                                             <span class="hljs-built_in">std</span>::memory_order_release)) {
        return_value.swap(next_node-&gt;data);
        <span class="hljs-keyword">delete</span> current_head;
        <span class="hljs-keyword">break</span>;
      }
    }
    <span class="hljs-keyword">return</span> return_value;
  }
</code></pre>
<p>Note: This queue doesn’t handle the <a target="_blank" href="https://en.wikipedia.org/wiki/ABA_problem">ABA problem</a>. It's out of the scope of this tutorial to bring in hazard pointers, so I’m leaving that out – but you can look into them if you're curious.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>So there you have it – atomics in C++. They're difficult to reason about but give you massive performance benefits. If you want to see production grade implementations of lock-free data structures, you can read more <a target="_blank" href="https://github.com/DNedic/lockfree">here</a>.</p>
<p>Typically, you'd see lock-based concurrent data structures put into production, but there is increasing research around the area of lock-free and wait-free implementations of concurrent algorithms to improve compute efficiency.</p>
<p>If you want to read this and other tutorials, you can visit my website <a target="_blank" href="https://redixhumayun.github.io/systems/2024/01/03/atomics-and-concurrency.html">here</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Concurrency in Kotlin Server-Side Development ]]>
                </title>
                <description>
                    <![CDATA[ By Faith Oyama Imagine you're running a bustling restaurant. Orders fly in, dishes need cooking, tables require clearing, and happy customers demand attention. How can you handle all this chaos without everything turning into a total disaster? This i... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/concurrency-in-kotlin-server-side-development/</link>
                <guid isPermaLink="false">66d45edb230dff01669057f3</guid>
                
                    <category>
                        <![CDATA[ concurrency ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Kotlin ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 05 Jan 2024 23:59:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/concurrency.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Faith Oyama</p>
<p>Imagine you're running a bustling restaurant. Orders fly in, dishes need cooking, tables require clearing, and happy customers demand attention. How can you handle all this chaos without everything turning into a total disaster? This is where concurrency comes in.</p>
<p>In the world of server-side development, things can get just as hectic. Users fire off requests, databases need querying, calculations demand crunching, and all this needs to happen smoothly and efficiently. Without concurrency, it's like having one overworked chef trying to do everything.</p>
<p>But with concurrency, it's like adding a whole team of skilled multitaskers to your kitchen. You have specialized "coroutines" handling different tasks – one taking orders, another cooking, one washing dishes, and so on. Each works simultaneously, but in a coordinated way, ensuring your customers get their delicious meals fast and with a smile.</p>
<h2 id="heading-examples-of-concurrency">Examples of Concurrency</h2>
<p>Here are some real-world examples of how concurrency works in server-side development:</p>
<p><strong>Serving multiple users at once:</strong> Imagine your website gets slammed by eager shoppers during a flash sale. Without concurrency, each user request would have to wait its turn, leading to frustratingly slow loading times. </p>
<p>But with coroutines, multiple requests can be processed simultaneously, keeping everyone happy and shopping with ease.</p>
<p><strong>Processing data pipelines:</strong> Do you work with really large datasets? Concurrency can break them down and analyze them bit by bit.</p>
<p><strong>Handling asynchronous requests:</strong> Think of API calls, database queries, or file uploads. These often take time to complete. With concurrency, your main program doesn't have to sit and wait. It can launch separate coroutines to handle these requests and get back to other tasks, keeping everything running smoothly.</p>
<p>Concurrency isn't just some fancy buzzword – it's a powerful tool that lets you handle the ever-growing demands of server-side development with ease and efficiency. </p>
<p>Now, we'll dive deeper into the differences between threads and coroutines, the fundamental building blocks of concurrent programming in Kotlin.</p>
<h2 id="heading-threads-vs-coroutines">Threads vs. Coroutines</h2>
<p>Now, let's talk about the two main players on this team: threads and coroutines. </p>
<h3 id="heading-what-are-threads">What are Threads?</h3>
<p>Threads are powerful, and capable of handling complex tasks – but they're also a bit resource-hungry. Each thread requires its memory space and attention from the operating system. </p>
<p>This can be great for demanding tasks like breaking down big numbers or sending critical emails, but if you have too many threads running around, your server starts getting overwhelmed, leading to slowdowns and even crashes.</p>
<h3 id="heading-what-are-coroutines">What are Coroutines?</h3>
<p>Coroutines are lightweight, flexible, and able to switch between tasks in a flash. They don't need their dedicated tables, they share resources efficiently, and they can even pause their work gracefully if something else needs immediate attention. </p>
<p>Think of them as taking orders, checking on tables, and cleaning dishes – always contributing, but in a light and adaptable way.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/kotin.PNG" alt="Image" width="600" height="400" loading="lazy">
<em>Table showing differences bewteen threads and coroutines.</em></p>
<p>So, which of them should you choose? Well, it depends! For heavy lifting, threads are strong and reliable. But for the everyday hustle and bustle, coroutines are your agile friends. </p>
<p>Kotlin favours coroutines for concurrent programming because they're more efficient and easier to manage, especially when dealing with lots of asynchronous tasks.</p>
<h2 id="heading-how-to-launch-coroutines">How to Launch Coroutines</h2>
<p>In your server-side code, there are two main ways to launch coroutines.</p>
<h3 id="heading-launch-and-forget-using-the-launch-keyword">Launch and Forget: Using the <code>launch</code> Keyword</h3>
<p>This fires up a new coroutine and sends it off to its assigned task, but doesn't wait for it to finish. </p>
<p>Here's how it looks in code:</p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">updateCustomerOrder</span><span class="hljs-params">(
  orderId: <span class="hljs-type">Int</span>,
  newDish: <span class="hljs-type">String</span>
)</span></span> {
  launch {
    updateOrderInDatabase(orderId, newDish)
  }
  sendConfirmationEmail(orderId)
}
</code></pre>
<p>This is ideal for tasks that don't need immediate feedback. You can launch multiple coroutines like this without overloading your server, as they work independently and share resources efficiently.</p>
<h3 id="heading-wait-and-receive-the-async-keyword">Wait and Receive: The <code>async</code> Keyword</h3>
<p>Now, let's say you need to know the total bill before you can settle up with the customer. This is where <code>async</code> comes in. It's like sending an assistant to calculate the bill and then patiently waiting for them to return with the answer.</p>
<p>Here's how it works:</p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">calculateBill</span><span class="hljs-params">(orderId: <span class="hljs-type">Int</span>)</span></span>: <span class="hljs-built_in">Double</span> {
  <span class="hljs-keyword">val</span> billResult = async {
    calculateBillFromDatabase(orderId)
  }
  <span class="hljs-keyword">val</span> totalBill = billResult.await()
  <span class="hljs-keyword">return</span> totalBill
}
</code></pre>
<p>This is useful for tasks where you need the result before proceeding. The <code>async</code> keyword creates a coroutine that calculates the bill in the background (performs the task), but the main program pauses and waits until the result is ready.</p>
<h2 id="heading-channels-communication-lifelines">Channels: Communication Lifelines</h2>
<p>Channels allow coroutines to send and receive messages in a safe and organized way, even when things get crazy. Here's how they work:</p>
<h3 id="heading-one-way-streets-send-channels">One-Way Streets: Send Channels</h3>
<p>A send channel allows one coroutine to send a message that another coroutine can receive on the other end. Only one direction, just like a one-way street.</p>
<h3 id="heading-bi-directional-bridges-receive-channels">Bi-Directional Bridges: Receive Channels</h3>
<p>Receive channels allow a coroutine to wait for and receive a message that was sent on the corresponding send channel. Two-way communication, like a bridge in both directions.</p>
<h3 id="heading-putting-channels-to-work">Putting Channels to Work:</h3>
<p>Here's an example of using channels to update customer orders:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> orderUpdatesChannel = Channel&lt;Pair&lt;<span class="hljs-built_in">Int</span>, String&gt;&gt;()

<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">updateCustomerOrder</span><span class="hljs-params">(orderId: <span class="hljs-type">Int</span>, newDish: <span class="hljs-type">String</span>)</span></span> {
  launch {
    updateOrderInDatabase(orderId, newDish)
    orderUpdatesChannel.send(orderId to newDish)
  }
}

<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">sendOrderConfirmationEmails</span><span class="hljs-params">()</span></span> {
  <span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>) {
    <span class="hljs-keyword">val</span> orderUpdate = orderUpdatesChannel.receive()
    <span class="hljs-keyword">val</span> (updatedOrderId, newDish) = orderUpdate
    sendConfirmationEmail(updatedOrderId)
  }
}
</code></pre>
<p>In this case, the <code>updateCustomerOrder</code> coroutine sends the updated order details through the <code>orderUpdatesChannel</code>. The <code>sendOrderConfirmationEmails</code> coroutine constantly waits on the channel, receiving updates one by one and sending out confirmation emails.</p>
<h2 id="heading-structured-concurrency">Structured Concurrency</h2>
<p>Think of structured concurrency like assigning roles and responsibilities in your kitchen. It helps you:</p>
<ol>
<li><strong>Define the scope:</strong> You can create coroutine contexts that provide specific resources and boundaries for your coroutines to work within. This keeps things organized and prevents rogue coroutines from mucking up the system.</li>
<li><strong>Cancellation:</strong> Imagine a customer changing their order halfway through cooking. Structured concurrency allows you to easily cancel the wrong dish and start preparing the new one, without everything crumbling into a greasy mess.</li>
<li><strong>Supervision:</strong> Structured concurrency lets you set up supervisors who monitor their "child" coroutines, ensuring they finish their tasks properly or handle errors gracefully.</li>
</ol>
<h3 id="heading-key-tools-for-structured-concurrency">Key tools for structured concurrency:</h3>
<p><strong>Dispatchers:</strong> They control where and how your coroutines run, like assigning them to specific threads or pools.</p>
<p><strong>Jobs:</strong> Think of them as the tasks themselves, assigned to specific coroutines within a context. You can track their progress, cancel them if needed, and keep things organized.</p>
<p><strong>Supervisor Jobs:</strong> They supervise child jobs, handling failures and propagating them properly, preventing errors from cascading and ruining the whole meal.</p>
<p>Different types of tasks in your server-side code demand different environments. This is where the various dispatcher types come in:</p>
<ol>
<li><strong>The Main Dispatcher:</strong> Think of it as the front of the house, handling UI updates and interacting directly with the customer (user). It's a single thread, ensuring smooth and responsive interactions without any chaotic multitasking.</li>
<li><strong>The Default Dispatcher:</strong> This is the workhorse for general computation tasks. It uses a thread pool, assigning coroutines to available threads. Great for CPU-intensive calculations, database processing, and other heavy lifting.</li>
<li><strong>The IO Dispatcher:</strong> This dispatcher handles blocking I/O operations like network calls, file access, or database queries. </li>
<li><strong>Custom Dispatchers:</strong> You can create custom dispatchers with specific thread pools or even single threads, tailoring them to the needs of your unique tasks.</li>
</ol>
<p>Choosing the right dispatcher is very important for optimizing performance and avoiding congestion. Here are some tips:</p>
<ul>
<li>Use the main dispatcher only for UI updates and user interaction.</li>
<li>Default dispatcher for most CPU-intensive tasks.</li>
<li>IO dispatcher for any blocking I/O operations.</li>
<li>Consider custom dispatchers for specific high-volume or sensitive tasks.</li>
</ul>
<h2 id="heading-flows">Flows</h2>
<p>Imagine your restaurant is booming, orders flying in faster than the chefs can cook. How do you handle this data deluge without everything turning into a soggy mess?</p>
<p>Think of Flows as streams of data flowing through your server-side code, like the continuous stream of orders coming from the tables. Instead of dealing with each dish individually, Flows let you handle the data continuously, adapting to the pace and transforming it on the fly.</p>
<p>Here's why Flows are a game-changer:</p>
<ul>
<li>No more waiting around for data to arrive. Flows let you launch coroutines to handle the stream asynchronously, keeping your main program free to keep taking orders and managing the overall experience.</li>
<li>Flows allow you to extract insights, generate reports, or trigger actions in real-time.</li>
<li>Flows automatically adjust their pace based on downstream processing capabilities, preventing backlogs and ensuring smooth data flow through your system.</li>
<li>Errors are handled delicately with flows, which transmit them without bringing down the entire service.</li>
</ul>
<p>Here's an example of using Flows to process a stream of sensor readings:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> sensorReadingsFlow = sensorManager.readings()
    .filter { reading -&gt; reading.temperature &gt; <span class="hljs-number">80</span> } 
    .map { reading -&gt; <span class="hljs-string">"Alert! Sensor <span class="hljs-subst">${reading.id}</span> at <span class="hljs-subst">${reading.temperature}</span> degrees!"</span> }    
    .launchIn(Dispatchers.IO) 
    .onEach { message -&gt; logger.warn(message) } 
    .collectLatest { message -&gt; sendPushNotification(message) }
</code></pre>
<p>This Flow reads sensor readings continuously, filters for high temperatures, transforms them into alert messages, and sends them to users, all in a non-blocking, resilient way.</p>
<p>Flows are a powerful tool for modern server-side development. They let you embrace the world of asynchronous data processing with grace and efficiency, keeping your code responsive, scalable, and ready to handle whatever data banquet your users throw at you.</p>
<h2 id="heading-testing-your-concurrency-setup">Testing Your Concurrency Setup</h2>
<p>So, you've built your server-side kitchen with agile coroutines, smooth communication channels, and efficient dispatchers. Your data flows like a rushing stream, and your customers (users) are singing your praises. But before you hang the "Open" sign permanently, there's one more crucial step: testing your concurrency magic.</p>
<p>Testing helps you uncover edge cases, prevent crashes, and ensure everything runs smoothly even under heavy load.</p>
<p>Here are some key points for testing concurrent code:</p>
<ul>
<li><strong>Focus on isolation:</strong> Test individual coroutines and channels in isolation to identify problems in specific components. You can use libraries like kotlinx-coroutines-test to control time and simulate asynchronous behavior.</li>
<li><strong>Mock dependencies:</strong> External dependencies like databases or APIs can add complexity. Mocking these dependencies allows you to focus on coroutine behavior without introducing real-world uncertainties.</li>
<li><strong>Verify state changes:</strong> Ensure coroutines update data structures and flags correctly as they execute. Assert expected values at different points in the execution flow.</li>
<li><strong>Stress test performance:</strong> Push your code to its limits with high volume or complex scenarios. This helps you identify bottlenecks and ensure your system scales gracefully.</li>
</ul>
<p>Remember, testing concurrent code is not always straightforward. Be patient, experiment with different methods, and don't be afraid to seek help from experienced developers and testing frameworks.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>We've explored agile coroutines dancing across tasks, efficient channels keeping them in sync, and smart dispatchers directing the flow. We've seen how Flows seamlessly handle data streams, and we've learned the importance of robust testing to ensure everything runs smoothly.</p>
<p>Now, with this knowledge, you should understand the concept of concurrency in your Kotlin applications. Embrace it, use it wisely, and watch your applications soar to new heights of responsiveness, scalability, and efficiency.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Concurrent Programming in Go – Goroutines, Channels, and More Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ By Rwitesh Bera Concurrency refers to a programming language's ability to deal with lots of things at once.  A good way to understand concurrency is by imagining multiple cars traveling on two lanes. Sometimes the cars overtake each other, and someti... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/concurrent-programming-in-go/</link>
                <guid isPermaLink="false">66d460c5733861e3a22a7359</guid>
                
                    <category>
                        <![CDATA[ concurrency ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Go Language ]]>
                    </category>
                
                    <category>
                        <![CDATA[ golang ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 21 Dec 2022 19:02:59 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/12/2-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Rwitesh Bera</p>
<p><strong>Concurrency</strong> refers to a programming language's ability to deal with lots of things at once. </p>
<p>A good way to understand concurrency is by imagining multiple cars traveling on two lanes. Sometimes the cars overtake each other, and sometimes they stop and let others pass by. </p>
<p>Another good example is when your computer runs multiple background tasks like messaging, downloading movies, running the operating system, and so on – all at once. </p>
<p><strong>Parallelism</strong> means doing lots of things simultaneously and independently. It might sound similar to concurrency, but it’s actually quite different. </p>
<p>Let's understand it better with the same traffic example. In this case, cars travel on their own road without intersecting each other. Each task is isolated from all other tasks. Concurrent tasks can be executed in any given order. </p>
<p>This is a non-deterministic way to achieve multiple things at once. True parallel events require multiple CPUs.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/12/1-1.png" alt="Image" width="600" height="400" loading="lazy">
<em>Illustration showing difference between parallelism and concurrency</em></p>
<h2 id="heading-what-is-a-goroutine">What is a Goroutine?</h2>
<p>A goroutine is an independent function that executes simultaneously in some separate lightweight threads managed by Go. GoLang provides it to support concurrency in Go.</p>
<p>Here's an example of what a goroutine looks like:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"fmt"</span>
    <span class="hljs-string">"time"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">go</span> helloworld()
    time.Sleep(<span class="hljs-number">1</span> * time.Second)
    goodbye()
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">helloworld</span><span class="hljs-params">()</span></span> {
    fmt.Println(<span class="hljs-string">"Hello World!"</span>)
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">goodbye</span><span class="hljs-params">()</span></span> {
    fmt.Println(<span class="hljs-string">"Good Bye!"</span>)
}
</code></pre>
<p>In this example, first, the <code>main</code> goroutine starts. Then it invokes the <code>helloworld()</code> function, and the <code>helloworld</code> goroutine starts. </p>
<p>After the <code>helloworld</code> goroutine finishes its operation, the <code>main</code> goroutine waits for 1 second and invokes the <code>goodbye()</code> function. </p>
<p>If you omit the <code>time</code> function in main, then it will exit before the <code>helloworld()</code> finishes its execution. </p>
<p>Let's understand the steps involved here:</p>
<ol>
<li><code>main</code> goroutine starts</li>
<li>Invokes <code>helloworld</code> and <code>helloworld</code> goroutine starts</li>
<li>If there is no pause using the sleep method, the <code>main</code> will then invoke <code>goodbye()</code> and exit before the <code>helloworld</code> goroutine finishes its execution.</li>
</ol>
<p>Without time.Sleep():</p>
<pre><code class="lang-bash">$ go run HelloWorld.go 
Good Bye!
</code></pre>
<p>After adding time.Sleep(), the <code>helloworld</code> goroutine is able to finish its execution before main exits:</p>
<pre><code class="lang-bash">$ go run HelloWorld.go 
Hello World!
Good Bye!
</code></pre>
<h3 id="heading-what-are-waitgroups">What are WaitGroups?</h3>
<p>You can use WaitGroups to wait for multiple goroutines to finish. A WaitGroup blocks the execution of a function until its internal counter becomes 0. </p>
<p>Let's see a simple code snippet:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"fmt"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">go</span> helloworld()
    <span class="hljs-keyword">go</span> goodbye()
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">helloworld</span><span class="hljs-params">()</span></span> {
    fmt.Println(<span class="hljs-string">"Hello World!"</span>)
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">goodbye</span><span class="hljs-params">()</span></span> {
    fmt.Println(<span class="hljs-string">"Good Bye!"</span>)
}
</code></pre>
<p>Output</p>
<pre><code class="lang-bash">$ go run HelloWorld.go 

$
</code></pre>
<p>If we run the above program, it doesn't print anything. This is because the main function got terminated as soon as those two goroutines started executing. So, we can use <code>Sleep</code> which pauses the execution of the main function. It looks like this:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"fmt"</span>
    <span class="hljs-string">"time"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">go</span> helloworld()
    <span class="hljs-keyword">go</span> goodbye()
    time.Sleep(<span class="hljs-number">2</span> * time.Second)
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">helloworld</span><span class="hljs-params">()</span></span> {
    fmt.Println(<span class="hljs-string">"Hello World!"</span>)
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">goodbye</span><span class="hljs-params">()</span></span> {
    fmt.Println(<span class="hljs-string">"Good Bye!"</span>)
}
</code></pre>
<p>Here's the output:</p>
<pre><code class="lang-bash">$ go run HelloWorld.go 
Good Bye!
Hello World!
</code></pre>
<p>Here, the <code>main</code> function was blocked for 2 seconds and all the goroutines were executed successfully. </p>
<p>Blocking the method for 2 seconds might not create any problems. But at the production level, where each millisecond is vital, millions of concurrent requests can create a huge problem.</p>
<p>You can solve this problem using <strong>sync.WaitGroup</strong> like this:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"fmt"</span>
    <span class="hljs-string">"sync"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">var</span> wg sync.WaitGroup
    wg.Add(<span class="hljs-number">2</span>)
    <span class="hljs-keyword">go</span> helloworld(&amp;wg)
    <span class="hljs-keyword">go</span> goodbye(&amp;wg)
    wg.Wait()
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">helloworld</span><span class="hljs-params">(wg *sync.WaitGroup)</span></span> {
    <span class="hljs-keyword">defer</span> wg.Done()
    fmt.Println(<span class="hljs-string">"Hello World!"</span>)
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">goodbye</span><span class="hljs-params">(wg *sync.WaitGroup)</span></span> {
    <span class="hljs-keyword">defer</span> wg.Done()
    fmt.Println(<span class="hljs-string">"Good Bye!"</span>)
}
</code></pre>
<p>Output</p>
<pre><code class="lang-bash">$ go run HelloWorld.go 
Good Bye!
Hello World!
</code></pre>
<p>The output is the same as the previous one, but it doesn't block the <code>main</code> for 2 seconds.</p>
<ol>
<li><code>wg.Add(int)</code>: This method indicates the number of goroutines to wait. In the above code, I have provided 2 for 2 different goroutines. Hence the internal counter wait becomes 2.</li>
<li><code>wg.Wait()</code>: This method blocks the execution of code until the internal counter becomes 0.</li>
<li><code>wg.Done()</code>: This will reduce the internal counter value by 1.</li>
</ol>
<p><strong>NOTE</strong>: If a WaitGroup is explicitly passed into functions, it should be added by a pointer.</p>
<h3 id="heading-what-are-channels">What are Channels?</h3>
<p>In concurrent programming, Go provides channels that you can use for bidirectional communication between goroutines. </p>
<p>Bidirectional communication means that one goroutine will send a message and the other will read it. Sends and receives are blocking. Code execution will be stopped until the write and read are done successfully. </p>
<p>Channels are one of the more convenient ways to send and receive notifications.</p>
<p>There are a couple different types of channels:</p>
<p><strong>Unbuffered channel</strong>: Unbuffered channels require both the sender and receiver to be present to be successful operations. It requires a goroutine to read the data, otherwise, it will lead to deadlock. By default, channels are unbuffered.</p>
<p><strong>Buffered channel</strong>: Buffered channels have the capacity to store values for future processing. The sender is not blocked until it becomes full and it doesn't necessarily need a reader to complete the synchronization with every operation. </p>
<p>If a space in the array is available, the sender can send its value to the channel and complete its send operation immediately. </p>
<p>After its execution, if a receiver comes, the channel will start sending values to the receiver and it will start its operation once it receives the values. As the sender and receiver are operating at different times, this is called <code>asynchronous communication</code>. </p>
<p>Here's an example:</p>
<pre><code class="lang-txt">Syntax to declare a channel
ch := make(chan Type)
</code></pre>
<pre><code class="lang-txt">Declaration of channels based on directions
1. Bidirectional channel : chan T
2. Send only channel: chan &lt;- T
3. Receive only channel: &lt;- chan T
</code></pre>
<h4 id="heading-how-to-write-and-read-from-a-channel">How to write and read from a channel</h4>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"fmt"</span>
    <span class="hljs-string">"time"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    msg := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>)
    <span class="hljs-keyword">go</span> greet(msg)
    time.Sleep(<span class="hljs-number">2</span> * time.Second)

    greeting := &lt;-msg

    time.Sleep(<span class="hljs-number">2</span> * time.Second)
    fmt.Println(<span class="hljs-string">"Greeting received"</span>)
    fmt.Println(greeting)
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">greet</span><span class="hljs-params">(ch <span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>)</span></span> {
    fmt.Println(<span class="hljs-string">"Greeter waiting to send greeting!"</span>)

    ch &lt;- <span class="hljs-string">"Hello Rwitesh"</span>

    fmt.Println(<span class="hljs-string">"Greeter completed"</span>)
}
</code></pre>
<pre><code class="lang-bash">$ go run main.go 
Greeter waiting to send greeting!
Greeter completed
Greeting received
Hello Rwitesh
</code></pre>
<p>In the above code snippet, <code>msg := make(chan string)</code> is declaring a channel of type string. Then I passed the channel in goroutine greet. <code>ch &lt;-"Hello Rwitesh"</code> allows us to write the message to <code>ch</code>.</p>
<p>The <code>ch &lt;-"Hello Rwitesh"</code> blocks the execution of the goroutine, as no one reads its value written in a channel. So in the <code>main</code> goroutine <code>time.Sleep(2 * time.Second)</code> terminates the execution without waiting for <code>greet</code>. </p>
<p>The second <code>time.Sleep(2* time.Second)</code> statement gives us the time to read from the channel. We read from the channel using <code>&lt;-msg</code>.</p>
<p><strong>Closing the channel</strong>: Closing the channel indicates that no more values should be sent on it. We want to show that the work has been completed and there is no need to keep a channel open.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"fmt"</span>
    <span class="hljs-string">"time"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    msg := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>)
    <span class="hljs-keyword">go</span> greet(msg)

    time.Sleep(<span class="hljs-number">2</span> * time.Second)

    greeting := &lt;-msg

    time.Sleep(<span class="hljs-number">2</span> * time.Second)
    fmt.Println(<span class="hljs-string">"Greeting received"</span>)
    fmt.Println(greeting)

    _, ok := &lt;-msg
    <span class="hljs-keyword">if</span> ok {
        fmt.Println(<span class="hljs-string">"Channel is open!"</span>)
    } <span class="hljs-keyword">else</span> {
        fmt.Println(<span class="hljs-string">"Channel is closed!"</span>)
    }
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">greet</span><span class="hljs-params">(ch <span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>)</span></span> {
    fmt.Println(<span class="hljs-string">"Greeter waiting to send greeting!"</span>)

    ch &lt;- <span class="hljs-string">"Hello Rwitesh"</span>
    <span class="hljs-built_in">close</span>(ch)

    fmt.Println(<span class="hljs-string">"Greeter completed"</span>)
}
</code></pre>
<p>We close a channel by using <code>close()</code> like <code>close(ch)</code> on the above code snippet.</p>
<pre><code class="lang-bash">$ go run main.go 
Greeter waiting to send greeting!
Greeter completed
Greeting received
Hello Rwitesh
Channel is closed!
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Let's recap what we've learned: concurrency in Go refers to the ability to perform multiple tasks simultaneously, using goroutines and tools like WaitGroups and channels to synchronize and communicate between them. </p>
<p>Goroutines are lightweight threads of execution used in Go to support concurrency. WaitGroups are used to wait for multiple goroutines to finish. They block the execution of a function until their internal counter becomes 0. </p>
<p>Channels are a way for goroutines to communicate and can be used to send and receive data between goroutines.</p>
<p>I hope you found this tutorial helpful and informative. If you enjoyed reading it, I encourage you to share it with your friends and followers on social media.</p>
<p>Don't forget to also follow me on <a target="_blank" href="https://twitter.com/RwiteshBera">Twitter</a> for more updates on coding and tech. Thanks for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Concurrency Explained: How to Build a Multi-Threaded iOS App ]]>
                </title>
                <description>
                    <![CDATA[ By Besher Al Maleh Concurrency in iOS is a massive topic. So in this article I want to zoom in on a sub-topic concerning queues and the Grand Central Dispatch (GCD) framework.  In particular, I wish to explore the differences between serial and concu... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/ios-concurrency/</link>
                <guid isPermaLink="false">66d45dd5d7a4e35e3843493f</guid>
                
                    <category>
                        <![CDATA[ concurrency ]]>
                    </category>
                
                    <category>
                        <![CDATA[ iOS ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 28 Jan 2020 01:24:39 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/03/onur-k-fHDVylCKLX0-unsplash-3.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Besher Al Maleh</p>
<p>Concurrency in iOS is a massive topic. So in this article I want to zoom in on a sub-topic concerning queues and the Grand Central Dispatch (GCD) framework. </p>
<p>In particular, I wish to explore the differences between serial and concurrent queues, as well as the differences between synchronous and asynchronous execution.</p>
<p>If you've never used GCD before, this article is a great place to start. If you have some experience with GCD, but are still curious about the topics mentioned above, I think you will still find it useful. And I hope you will pick up one or two new things along the way. </p>
<p>I created a SwiftUI companion app to visually demonstrate the concepts in this article. The app also has a fun short quiz that I encourage you to try before and after reading this article. <a target="_blank" href="https://github.com/almaleh/Dispatcher">Download the source code here</a>, or get the <a target="_blank" href="https://testflight.apple.com/join/2tC0CKMO">public beta here</a>.</p>
<p>I will begin with an introduction to GCD, followed by a detailed explanation on sync, async, serial and concurrent. Afterwards, I will cover some pitfalls when working with concurrency. Finally, I will end with a summary and some general advice.</p>
<h2 id="heading-introduction">Introduction</h2>
<p>Let’s start with a brief intro to GCD and dispatch queues. Feel free to skip to the <strong>Sync vs Async</strong> section if you are already familiar with the topic.</p>
<h3 id="heading-concurrency-and-grand-central-dispatch">Concurrency and Grand Central Dispatch</h3>
<p>Concurrency lets you take advantage of the fact that your device has multiple CPU cores. To make use of these cores, you will need to use multiple threads. However, threads are a low-level tool, and managing threads manually in an efficient manner is extremely difficult.</p>
<p><a target="_blank" href="https://developer.apple.com/documentation/DISPATCH">Grand Central Dispatch</a> was created by Apple over 10 years ago as an abstraction to help developers write multi-threaded code without manually creating and managing the threads themselves.</p>
<p>With GCD, Apple took an <a target="_blank" href="https://developer.apple.com/library/archive/documentation/General/Conceptual/ConcurrencyProgrammingGuide/ConcurrencyandApplicationDesign/ConcurrencyandApplicationDesign.html#//apple_ref/doc/uid/TP40008091-CH100-SW8"><em>asynchronous design approach</em></a> to the problem. Instead of creating threads directly, you use GCD to schedule work tasks, and the system will perform these tasks for you by making the best use of its resources. GCD will handle creating the requisite threads and will schedule your tasks on those threads, shifting the burden of thread management from the developer to the system.</p>
<p>A big advantage of GCD is that you don’t have to worry about hardware resources as you write your concurrent code. GCD manages a thread pool for you, and it will scale from a single-core Apple Watch all the way up to a many-core MacBook Pro.</p>
<h3 id="heading-dispatch-queues">Dispatch Queues</h3>
<p>These are the main building blocks of GCD which let you execute arbitrary blocks of code using a set of parameters that you define. The tasks in dispatch queues are always started in a first-in, first-out (FIFO) fashion. Note that I said <em>started</em>, because the completion time of your tasks depends on several factors, and is not guaranteed to be FIFO (more on that later.)</p>
<p>Broadly speaking, there are three kinds of queues available to you:</p>
<ul>
<li>The Main dispatch queue (serial, pre-defined)</li>
<li>Global queues (concurrent, pre-defined)</li>
<li>Private queues (can be serial or concurrent, you create them)</li>
</ul>
<p>Every app comes with a Main queue, which is a <em>serial</em> queue that executes tasks on the main thread. This queue is responsible for drawing your application’s UI and responding to user interactions (touch, scroll, pan, etc.) If you block this queue for too long, your iOS app will appear to freeze, and your macOS app will display the infamous beach ball/spinning wheel.</p>
<p>When performing a long-running task (network call, computationally intensive work, etc), we avoid freezing the UI by performing this work on a background queue. Then we update the UI with the results on the main queue:</p>
<pre><code class="lang-swift"><span class="hljs-type">URLSession</span>.shared.dataTask(with: url) { data, response, error <span class="hljs-keyword">in</span>
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> data = data {
        <span class="hljs-type">DispatchQueue</span>.main.async { <span class="hljs-comment">// UI work</span>
            <span class="hljs-keyword">self</span>.label.text = <span class="hljs-type">String</span>(data: data, encoding: .utf8)
        }
    }
}
</code></pre>
<p>As a rule of thumb, all UI work must be executed on the Main queue. You can turn on the Main Thread Checker option in Xcode to receive warnings whenever UI work gets executed on a background thread.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/01/1-HwivHHBJZKmFzhQfiJZ3nQ.png" alt="the main thread checker can be found in the scheme editor" width="600" height="400" loading="lazy"></p>
<p>In addition to the main queue, every app comes with several pre-defined concurrent queues that have varying levels of <a target="_blank" href="https://developer.apple.com/library/archive/documentation/Performance/Conceptual/EnergyGuide-iOS/PrioritizeWorkWithQoS.html">Quality of Service</a> (an abstract notion of priority in GCD.)</p>
<p>For example, here’s the code to submit work asynchronously to the <em>user interactive</em> (highest priority) QoS queue:</p>
<pre><code class="lang-swift"><span class="hljs-type">DispatchQueue</span>.global(qos: .userInteractive).async {
    <span class="hljs-built_in">print</span>(<span class="hljs-string">"We're on a global concurrent queue!"</span>) 
}
</code></pre>
<p>Alternatively, you can call the <em>default priority</em> global queue by not specifying a QoS like this:</p>
<pre><code class="lang-swift"><span class="hljs-type">DispatchQueue</span>.global().async {
    <span class="hljs-built_in">print</span>(<span class="hljs-string">"Generic global queue"</span>)
}
</code></pre>
<p>Additionally, you can create your own private queues using the following syntax:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> serial = <span class="hljs-type">DispatchQueue</span>(label: <span class="hljs-string">"com.besher.serial-queue"</span>)
serial.async {
    <span class="hljs-built_in">print</span>(<span class="hljs-string">"Private serial queue"</span>)
}
</code></pre>
<p>When creating private queues, it helps to use a descriptive label (such as reverse DNS notation), as this will aid you while debugging in Xcode’s navigator, lldb, and Instruments:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/01/1-vri5m4HJq2CBLeTUYg-RTQ-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/01/1-zc_ZBGW9gVUF4h7TQA5Lgw.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>By default, private queues are <em>serial</em> (I’ll explain what this means shortly, promise!) If you want to create a private <em>concurrent</em> queue, you can do so via the optional <em>attributes</em> parameter:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> concurrent = <span class="hljs-type">DispatchQueue</span>(label: <span class="hljs-string">"com.besher.serial-queue"</span>, attributes: .concurrent)
concurrent.sync {
    <span class="hljs-built_in">print</span>(<span class="hljs-string">"Private concurrent queue"</span>)
}
</code></pre>
<p>There is an optional QoS parameter as well. The private queues that you create will ultimately land in one of the global concurrent queues based on their given parameters.</p>
<h3 id="heading-whats-in-a-task">What’s in a task?</h3>
<p>I mentioned dispatching tasks to queues. Tasks can refer to any block of code that you submit to a queue using the <code>sync</code> or <code>async</code> functions. They can be submitted in the form of an anonymous closure:</p>
<pre><code class="lang-swift"><span class="hljs-type">DispatchQueue</span>.global().async {
    <span class="hljs-built_in">print</span>(<span class="hljs-string">"Anonymous closure"</span>)
}
</code></pre>
<p>Or inside a <a target="_blank" href="https://developer.apple.com/documentation/dispatch/dispatchworkitem">dispatch work item</a> that gets performed later:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> item = <span class="hljs-type">DispatchWorkItem</span>(qos: .utility) {
    <span class="hljs-built_in">print</span>(<span class="hljs-string">"Work item to be executed later"</span>)
}
</code></pre>
<p>Regardless of whether you dispatch synchronously or asynchronously, and whether you choose a serial or concurrent queue, all of the code inside a single task will execute line by line. Concurrency is only relevant when evaluating <em>multiple</em> tasks.</p>
<p>For example, if you have 3 loops inside the <strong>same</strong> task, these loops will <em>always</em> execute in order:</p>
<pre><code class="lang-swift"><span class="hljs-type">DispatchQueue</span>.global().async {
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-number">0</span>..&lt;<span class="hljs-number">10</span> {
        <span class="hljs-built_in">print</span>(i)
    }

    <span class="hljs-keyword">for</span> <span class="hljs-number">_</span> <span class="hljs-keyword">in</span> <span class="hljs-number">0</span>..&lt;<span class="hljs-number">10</span> {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"?"</span>)
    }

    <span class="hljs-keyword">for</span> <span class="hljs-number">_</span> <span class="hljs-keyword">in</span> <span class="hljs-number">0</span>..&lt;<span class="hljs-number">10</span> {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"?"</span>)
    }
}
</code></pre>
<p>This code always prints out ten digits from 0 to 9, followed by ten blue circles, followed by ten broken hearts, regardless of how you dispatch that closure.</p>
<p>Individual tasks can also have their own QoS level as well (by default they use their queue’s priority.) This distinction between queue QoS and task QoS leads to some interesting behaviour that we will discuss in the priority inversion section.</p>
<p>By now you might be wondering what <em>serial</em> and <em>concurrent</em> are all about. You might also be wondering about the differences between <code>sync</code> and <code>async</code> when submitting your tasks. This brings us to the crux of this article, so let’s dive in!</p>
<h2 id="heading-sync-vs-async">Sync vs Async</h2>
<p>When you dispatch a task to a queue, you can choose to do so synchronously or asynchronously using the <code>sync</code> and <code>async</code> dispatch functions. Sync and async primarily affect the <strong>source</strong> of the submitted task, that is the queue where it is being submitted <em>from</em>.</p>
<p>When your code reaches a <code>sync</code> statement, it will block the current queue until that task completes. Once the task returns/completes, control is returned to the caller, and the code that follows the <code>sync</code> task will continue.</p>
<p>Think of <code>sync</code> as synonymous with ‘blocking’.</p>
<p>An <code>async</code> statement, on the other hand, will execute asynchronously with respect to the current queue, and immediately returns control back to the caller without waiting for the contents of the <code>async</code> closure to execute. There is no guarantee as to when exactly the code inside that async closure will execute.</p>
<h3 id="heading-current-queue">Current queue?</h3>
<p>It may not be obvious what the source, or <em>current</em>, queue is, because it’s not always explicitly defined in the code. </p>
<p>For example, if you call your <code>sync</code> statement inside viewDidLoad, your current queue will be the Main dispatch queue. If you call the same function inside a URLSession completion handler, your current queue will be a background queue.</p>
<p>Going back to sync vs async, let’s take this example:</p>
<pre><code class="lang-swift"><span class="hljs-type">DispatchQueue</span>.global().sync {
    <span class="hljs-built_in">print</span>(<span class="hljs-string">"Inside"</span>)
}
<span class="hljs-built_in">print</span>(<span class="hljs-string">"Outside"</span>)
<span class="hljs-comment">// Console output:</span>
<span class="hljs-comment">// Inside</span>
<span class="hljs-comment">// Outside</span>
</code></pre>
<p>The above code will block the current queue, enter the closure and execute its code on the global queue by printing “Inside”, before proceeding to print “Outside”. This order is guaranteed.</p>
<p>Let’s see what happens if we try <code>async</code> instead:</p>
<pre><code class="lang-swift"><span class="hljs-type">DispatchQueue</span>.global().async {
    <span class="hljs-built_in">print</span>(<span class="hljs-string">"Inside"</span>)
}
<span class="hljs-built_in">print</span>(<span class="hljs-string">"Outside"</span>)
<span class="hljs-comment">// Potential console output (based on QoS): </span>
<span class="hljs-comment">// Outside</span>
<span class="hljs-comment">// Inside</span>
</code></pre>
<p>Our code now submits the closure to the global queue, then immediately proceeds to run the next line. It will <em>likely</em> print “Outside” before “Inside”, but this order isn’t guaranteed. It depends on the QoS of the source and destination queues, as well as other factors that the system controls.</p>
<p>Threads are an implementation detail in GCD — we do not have direct control over them and can only deal with them using queue abstractions. Nevertheless, I think it can be useful to ‘peek under the covers’ at thread behaviour to understand some challenges we might encounter with GCD.</p>
<p>For instance, when you submit a task using <code>sync</code>, <a target="_blank" href="https://developer.apple.com/documentation/dispatch/1452870-dispatch_sync?language=objc">GCD optimizes performance by executing that task on the current thread</a> (the caller.) </p>
<p>There is one exception however, which is when you submit a sync task to the main queue —  doing so will always run the task on the main thread and not the caller. This behaviour can have some ramifications that we will explore in the priority inversion section.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/01/Sync-400.gif" alt="Image" width="600" height="400" loading="lazy">
<em>[From Dispatcher on Github](https://github.com/almaleh/Dispatcher" rel="noopener nofollow)</em></p>
<h3 id="heading-which-one-to-use">Which one to use?</h3>
<p>When submitting work to a queue, <a target="_blank" href="https://developer.apple.com/library/archive/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html#//apple_ref/doc/uid/TP40008091-CH102-SW21">Apple recommends using asynchronous execution over synchronous execution</a>. However, there are situations where <code>sync</code> might be the better choice, such as when dealing with race conditions, or when performing a very small task. I will cover these situations shortly.</p>
<p>One large consequence of performing work asynchronously inside a function is that the function can no longer directly return its values (if they depend on the async work that’s being done). It must instead use a closure/completion handler parameter to deliver the results.</p>
<p>To demonstrate this concept, let’s take a small function that accepts image data, performs some expensive computation to process the image, then returns the result:</p>
<pre><code class="lang-swift"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">processImage</span><span class="hljs-params">(data: Data)</span></span> -&gt; <span class="hljs-type">UIImage?</span> {
    <span class="hljs-keyword">guard</span> <span class="hljs-keyword">let</span> image = <span class="hljs-type">UIImage</span>(data: data) <span class="hljs-keyword">else</span> { <span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span> }
    <span class="hljs-comment">// calling an expensive function</span>
    <span class="hljs-keyword">let</span> processedImage = upscaleAndFilter(image: image)
    <span class="hljs-keyword">return</span> processedImage 
}
</code></pre>
<p>In this example, the function <code>upscaleAndFilter(image:)</code> might take several seconds, so we want to offload it into a separate queue to avoid freezing the UI. Let’s create a dedicated queue for image processing, and then dispatch the expensive function asynchronously:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> imageProcessingQueue = <span class="hljs-type">DispatchQueue</span>(label: <span class="hljs-string">"com.besher.image-processing"</span>)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">processImageAsync</span><span class="hljs-params">(data: Data)</span></span> -&gt; <span class="hljs-type">UIImage?</span> {
    <span class="hljs-keyword">guard</span> <span class="hljs-keyword">let</span> image = <span class="hljs-type">UIImage</span>(data: data) <span class="hljs-keyword">else</span> { <span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span> }

    imageProcessingQueue.async {
        <span class="hljs-keyword">let</span> processedImage = upscaleAndFilter(image: image)
        <span class="hljs-keyword">return</span> processedImage
    }
}
</code></pre>
<p>There are two issues with this code. First, the return statement is inside the async closure, so it is no longer returning a value to the <code>processImageAsync(data:)</code> function, and currently serves no purpose. </p>
<p>But the bigger issue is that our <code>processImageAsync(data:)</code> function is no longer returning any value, because the function reaches the end of its body before it enters the <code>async</code> closure.</p>
<p>To fix this error, we will adjust the function so that it no longer directly returns a value. Instead, it will have a new completion handler parameter that we can call once our asynchronous function has completed its work:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> imageProcessingQueue = <span class="hljs-type">DispatchQueue</span>(label: <span class="hljs-string">"com.besher.image-processing"</span>)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">processImageAsync</span><span class="hljs-params">(data: Data, completion: @escaping <span class="hljs-params">(UIImage?)</span></span></span> -&gt; <span class="hljs-type">Void</span>) {
    <span class="hljs-keyword">guard</span> <span class="hljs-keyword">let</span> image = <span class="hljs-type">UIImage</span>(data: data) <span class="hljs-keyword">else</span> {
        completion(<span class="hljs-literal">nil</span>)
        <span class="hljs-keyword">return</span>
    }

    imageProcessingQueue.async {
        <span class="hljs-keyword">let</span> processedImage =  <span class="hljs-keyword">self</span>.upscaleAndFilter(image: image)
        completion(processedImage)
    }
}
</code></pre>
<p>As evident in this example, the change to make the function asynchronous has propagated to its caller, who now has to pass in a closure and handle the results asynchronously as well. By introducing an asynchronous task, you can potentially end up modifying a chain of several functions.</p>
<p>Concurrency and asynchronous execution add complexity to your project as we just observed. This indirection also makes debugging more difficult. That’s why it really pays off to think about concurrency early in your design — it’s not something you want to tack on at the end of your design cycle.</p>
<p>Synchronous execution, by contrast, does not increase complexity. Rather, it allows you to continue using return statements as you did before. A function containing a <code>sync</code> task will not return until the code inside that task has completed. Therefore it does not require a completion handler.</p>
<p>If you are submitting a tiny task (for example, updating a value), consider doing it synchronously. Not only does that help you keep your code simple, it will also perform better — Async is believed to <a target="_blank" href="https://gist.github.com/tclementdev/6af616354912b0347cdf6db159c37057">incur an overhead</a> that outweighs the benefit of doing the work asynchronously for tiny tasks that take under 1ms to complete.</p>
<p>If you are submitting a large task, however, like the image processing we performed above, then consider doing it asynchronously to avoid blocking the caller for too long.</p>
<h3 id="heading-dispatching-on-the-same-queue">Dispatching on the same queue</h3>
<p>While it is safe to dispatch a task asynchronously from a queue into itself (for example, you can use <a target="_blank" href="https://developer.apple.com/documentation/dispatch/dispatchqueue/2300020-asyncafter">.asyncAfter</a> on the current queue), you can not dispatch a task <em>synchronously</em> from a queue into the same queue. Doing so will result in a deadlock that immediately crashes the app!</p>
<p>This issue can manifest itself when performing a chain of synchronous calls that lead back to the original queue. That is, you <code>sync</code> a task onto another queue, and when the task completes, it syncs the results back into the original queue, leading to a deadlock. Use <code>async</code> to avoid such crashes.</p>
<h3 id="heading-blocking-the-main-queue">Blocking the main queue</h3>
<p>Dispatching tasks synchronously <em>from</em> the main queue will block that queue, thereby freezing the UI, until the task is completed. Thus it’s better to avoid dispatching work synchronously from the main queue unless you’re performing really light work.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/01/Async-400.gif" alt="Image" width="600" height="400" loading="lazy">
<em>[prefer to use async from the main queue](https://github.com/almaleh/Dispatcher" rel="noopener nofollow)</em></p>
<h2 id="heading-serial-vs-concurrent">Serial vs Concurrent</h2>
<p><em>Serial</em> and <em>concurrent</em> affect the <strong>destination</strong> —  the queue in which your work has been submitted to run. This is in contrast to <em>sync</em> and <em>async</em>, which affected the <strong>source</strong>.</p>
<p>A serial queue will not execute its work on more than one thread at a time, regardless of how many tasks you dispatch on that queue. Consequently, the tasks are guaranteed to not only start, but also terminate, in first-in, first-out order. </p>
<p>Moreover, when you block a serial queue (using a <code>sync</code> call, semaphore, or some other tool), all work on that queue will halt until the block is over.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/01/Serial-400.gif" alt="Image" width="600" height="400" loading="lazy">
<em>[From Dispatcher on Github](https://github.com/almaleh/Dispatcher" rel="noopener nofollow)</em></p>
<p>A concurrent queue can spawn multiple threads, and the system decides how many threads are created. Tasks always <em>start</em> in FIFO order, but the queue does not wait for tasks to finish before starting the next task, therefore tasks on concurrent queues can finish in any order. </p>
<p>When you perform a blocking command on a concurrent queue, it will not block the other threads on this queue. Additionally, when a concurrent queue gets blocked, it runs the risk of <em>thread explosion</em>. I will cover this in more detail later on.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/01/Concurrent-400.gif" alt="Image" width="600" height="400" loading="lazy">
<em>[From Dispatcher on Github](https://github.com/almaleh/Dispatcher" rel="noopener nofollow)</em></p>
<p>The main queue in your app is serial. All the global pre-defined queues are concurrent. Any private dispatch queue you create is serial by default, but can be set to be concurrent using an optional attribute as discussed earlier.</p>
<p>It’s important to note here that the concept of <em>serial</em> vs <em>concurrent</em> is only relevant when discussing a specific queue. All queues are concurrent relative to <em>each other</em>. </p>
<p>That is, if you dispatch work asynchronously from the main queue to a private <em>serial</em> queue, that work will be completed <em>concurrently</em> with respect to the main queue. And if you create two different serial queues, and then perform blocking work on one of them, the other queue is unaffected.</p>
<p>To demonstrate the concurrency of multiple serial queues, let’s take this example:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> serial1 = <span class="hljs-type">DispatchQueue</span>(label: <span class="hljs-string">"com.besher.serial1"</span>)
<span class="hljs-keyword">let</span> serial2 = <span class="hljs-type">DispatchQueue</span>(label: <span class="hljs-string">"com.besher.serial2"</span>)

serial1.async {
    <span class="hljs-keyword">for</span> <span class="hljs-number">_</span> <span class="hljs-keyword">in</span> <span class="hljs-number">0</span>..&lt;<span class="hljs-number">5</span> { <span class="hljs-built_in">print</span>(<span class="hljs-string">"?"</span>) }
}

serial2.async {
    <span class="hljs-keyword">for</span> <span class="hljs-number">_</span> <span class="hljs-keyword">in</span> <span class="hljs-number">0</span>..&lt;<span class="hljs-number">5</span> { <span class="hljs-built_in">print</span>(<span class="hljs-string">"?"</span>) }
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/01/1-zJztLeessQUMvONpoLW0ZQ.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Both queues here are serial, but the results are jumbled up because they execute concurrently in relation to each other. The fact that they’re each serial (or concurrent) has no effect on this result. Their QoS level determines who will <em>generally</em> finish first (order not guaranteed).</p>
<p>If we want to ensure that the first loop finishes first before starting the second loop, we can submit the first task synchronously from the caller:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> serial1 = <span class="hljs-type">DispatchQueue</span>(label: <span class="hljs-string">"com.besher.serial1"</span>)
<span class="hljs-keyword">let</span> serial2 = <span class="hljs-type">DispatchQueue</span>(label: <span class="hljs-string">"com.besher.serial2"</span>)

serial1.sync { <span class="hljs-comment">// &lt;---- we changed this to 'sync'</span>
    <span class="hljs-keyword">for</span> <span class="hljs-number">_</span> <span class="hljs-keyword">in</span> <span class="hljs-number">0</span>..&lt;<span class="hljs-number">5</span> { <span class="hljs-built_in">print</span>(<span class="hljs-string">"?"</span>) }
}
<span class="hljs-comment">// we don't get here until first loop terminates</span>
serial2.async {
    <span class="hljs-keyword">for</span> <span class="hljs-number">_</span> <span class="hljs-keyword">in</span> <span class="hljs-number">0</span>..&lt;<span class="hljs-number">5</span> { <span class="hljs-built_in">print</span>(<span class="hljs-string">"?"</span>) }
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/01/1-s1N-5HfXpcAtsKQ3tZ-DHQ-2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This is not necessarily desirable, because we are now blocking the caller while the first loop is executing.</p>
<p>To avoid blocking the caller, we can submit both tasks asynchronously, but to the <em>same</em> serial queue:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> serial = <span class="hljs-type">DispatchQueue</span>(label: <span class="hljs-string">"com.besher.serial"</span>)

serial.async {
    <span class="hljs-keyword">for</span> <span class="hljs-number">_</span> <span class="hljs-keyword">in</span> <span class="hljs-number">0</span>..&lt;<span class="hljs-number">5</span> { <span class="hljs-built_in">print</span>(<span class="hljs-string">"?"</span>) }
}

serial.async {
    <span class="hljs-keyword">for</span> <span class="hljs-number">_</span> <span class="hljs-keyword">in</span> <span class="hljs-number">0</span>..&lt;<span class="hljs-number">5</span> { <span class="hljs-built_in">print</span>(<span class="hljs-string">"?"</span>) }
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/01/1-s1N-5HfXpcAtsKQ3tZ-DHQ-2-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now our tasks execute concurrently with respect to the <em>caller</em>, while also keeping their order intact.</p>
<p>Note that if we make our single queue concurrent via the optional parameter, we go back to the jumbled results, as expected:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> concurrent = <span class="hljs-type">DispatchQueue</span>(label: <span class="hljs-string">"com.besher.concurrent"</span>, attributes: .concurrent)

concurrent.async {
    <span class="hljs-keyword">for</span> <span class="hljs-number">_</span> <span class="hljs-keyword">in</span> <span class="hljs-number">0</span>..&lt;<span class="hljs-number">5</span> { <span class="hljs-built_in">print</span>(<span class="hljs-string">"?"</span>) }
}

concurrent.async {
    <span class="hljs-keyword">for</span> <span class="hljs-number">_</span> <span class="hljs-keyword">in</span> <span class="hljs-number">0</span>..&lt;<span class="hljs-number">5</span> { <span class="hljs-built_in">print</span>(<span class="hljs-string">"?"</span>) }
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/01/1-zJztLeessQUMvONpoLW0ZQ-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Sometimes you might confuse synchronous execution with serial execution (at least I did), but they are very different things. For example, try changing the first dispatch on line 3 from our previous example to a <code>sync</code> call:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> concurrent = <span class="hljs-type">DispatchQueue</span>(label: <span class="hljs-string">"com.besher.concurrent"</span>, attributes: .concurrent)

concurrent.sync {
    <span class="hljs-keyword">for</span> <span class="hljs-number">_</span> <span class="hljs-keyword">in</span> <span class="hljs-number">0</span>..&lt;<span class="hljs-number">5</span> { <span class="hljs-built_in">print</span>(<span class="hljs-string">"?"</span>) }
}

concurrent.async {
    <span class="hljs-keyword">for</span> <span class="hljs-number">_</span> <span class="hljs-keyword">in</span> <span class="hljs-number">0</span>..&lt;<span class="hljs-number">5</span> { <span class="hljs-built_in">print</span>(<span class="hljs-string">"?"</span>) }
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/01/1-s1N-5HfXpcAtsKQ3tZ-DHQ.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Suddenly, our results are back in perfect order. But this is a concurrent queue, so how could that happen? Did the <code>sync</code> statement somehow turn it into a serial queue?</p>
<p>The answer is <strong>no!</strong></p>
<p>This is a bit sneaky. What happened is that we did not reach the <code>async</code> call until the first task had completed its execution. The queue is still very much concurrent, but inside this zoomed-in section of the code. it appears as if it were serial. This is because we are blocking the caller, and not proceeding to the next task, until the first one is finished.</p>
<p>If another queue somewhere else in your app tried submitting work to this same queue while it was still executing the <code>sync</code> statement, that work <em>will</em> run concurrently with whatever we got running here, because it’s still a concurrent queue.</p>
<h3 id="heading-which-one-to-use-1">Which one to use?</h3>
<p>Serial queues take advantage of CPU optimizations and caching, and help reduce context switching. </p>
<p>Apple recommends starting with one serial queue per subsystem in your app —  for example one for networking, one for file compression, etc. If the need arises, you can later expand to a <a target="_blank" href="https://developer.apple.com/videos/play/wwdc2017/706/">hierarchy of queues per subsystem</a> using the <a target="_blank" href="https://developer.apple.com/documentation/dispatch/dispatchobject/1452989-settarget">setTarget method</a> or the <a target="_blank" href="https://developer.apple.com/documentation/dispatch/dispatchqueue/2300059-init">optional target parameter</a> when building queues.</p>
<p>If you run into a performance bottleneck, measure your app’s performance then see if a concurrent queue helps. If you do not see a measurable benefit, it’s better to stick to serial queues.</p>
<h2 id="heading-pitfalls">Pitfalls</h2>
<h3 id="heading-priority-inversion-and-quality-of-service">Priority Inversion and Quality of Service</h3>
<p><a target="_blank" href="https://en.wikipedia.org/wiki/Priority_inversion">Priority inversion</a> is when a high priority task is prevented from running by a lower priority task, effectively inverting their relative priorities.</p>
<p>This situation often occurs when a high QoS queue shares a resources with a low QoS queue, and the low QoS queue gets a lock on that resource. </p>
<p>But I wish to cover a different scenario that is more relevant to our discussion —  it’s when you submit tasks to a low QoS serial queue, then submit a high QoS task to that same queue. This scenario also results in priority inversion, because the high QoS task has to wait on the lower QoS tasks to finish.</p>
<p>GCD resolves priority inversion by temporarily raising the QoS of the queue that contains the low priority tasks that are ‘ahead’ of, or blocking, your high priority task. </p>
<p>It’s kind of like having cars stuck <em>in front</em> <em>of</em> an ambulance. Suddenly they’re allowed to cross the red light just so that the ambulance can move (in reality the cars move to the side, but imagine a narrow (serial) street or something, you get the point :-P)</p>
<p>To illustrate the inversion problem, let’s start with this code:</p>
<pre><code class="lang-swift">
<span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">Color</span>: <span class="hljs-title">String</span> </span>{
    <span class="hljs-keyword">case</span> blue = <span class="hljs-string">"?"</span>
    <span class="hljs-keyword">case</span> white = <span class="hljs-string">"⚪️"</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">output</span><span class="hljs-params">(color: Color, times: Int)</span></span> {
    <span class="hljs-keyword">for</span> <span class="hljs-number">_</span> <span class="hljs-keyword">in</span> <span class="hljs-number">1</span>...times {
        <span class="hljs-built_in">print</span>(color.rawValue)
    }
}

<span class="hljs-keyword">let</span> starterQueue = <span class="hljs-type">DispatchQueue</span>(label: <span class="hljs-string">"com.besher.starter"</span>, qos: .userInteractive)
<span class="hljs-keyword">let</span> utilityQueue = <span class="hljs-type">DispatchQueue</span>(label: <span class="hljs-string">"com.besher.utility"</span>, qos: .utility)
<span class="hljs-keyword">let</span> backgroundQueue = <span class="hljs-type">DispatchQueue</span>(label: <span class="hljs-string">"com.besher.background"</span>, qos: .background)
<span class="hljs-keyword">let</span> <span class="hljs-built_in">count</span> = <span class="hljs-number">10</span>

starterQueue.async {

    backgroundQueue.async {
        output(color: .white, times: <span class="hljs-built_in">count</span>)
    }

    backgroundQueue.async {
        output(color: .white, times: <span class="hljs-built_in">count</span>)
    }

    utilityQueue.async {
        output(color: .blue, times: <span class="hljs-built_in">count</span>)
    }

    utilityQueue.async {
        output(color: .blue, times: <span class="hljs-built_in">count</span>)
    }

    <span class="hljs-comment">// next statement goes here</span>
}
</code></pre>
<p>We create a starter queue (where we submit the tasks <em>from</em>), as well as two queues with different QoS. Then we dispatch tasks to each of these two queues, each task printing out an equal number of circles of a specific colour (<em>utility</em> queue is blue, <em>background</em> is white.)</p>
<p>Because these tasks are submitted asynchronously, every time you run the app, you’re going to see slightly different results. However, as you would expect, the queue with the lower QoS (background) almost always finishes last. In fact, the last 10–15 circles are usually all white.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/01/1-woRLw218x4QZKFov0w1hDA.gif" alt="Image" width="600" height="400" loading="lazy">
<em>no surprises here</em></p>
<p>But watch what happens when we submit a <strong>sync</strong> task to the background queue after the last async statement. You don’t even need to print anything inside the <code>sync</code> statement, just adding this line is enough:</p>
<pre><code class="lang-swift"><span class="hljs-comment">// add this after the last async statement, </span>
<span class="hljs-comment">// still inside starterQueue.async</span>
backgroundQueue.sync {}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/01/1-yxMCgE4Vy8Ws2309CvYelA.gif" alt="Image" width="600" height="400" loading="lazy">
<em>priority inversion</em></p>
<p>The results in the console have flipped! Now, the higher priority queue (utility) always finishes last, and the last 10–15 circles are <em>blue.</em></p>
<p>To understand why that happens, we need to revisit the fact that synchronous work is executed on the caller thread (unless you’re submitting to the main queue.) </p>
<p>In our example above, the caller (starterQueue) has the top QoS (userInteractive.) Therefore, that seemingly innocuous <code>sync</code> task is not only blocking the starter queue, but it’s also running on the starter’s high QoS thread. The task therefore runs with high QoS, but there are two other tasks ahead of it on the same background queue that have <em>background</em> QoS. Priority inversion detected!</p>
<p>As expected, GCD resolves this inversion by raising the QoS of the entire queue to temporarily match the high QoS task. Consequently, all the tasks on the background queue end up running at <em>user interactive</em> QoS, which is higher than the <em>utility</em> QoS. And that’s why the utility tasks finish last!</p>
<p>Side-note: If you remove the starter queue from that example and submit from the main queue instead, you will get similar results, as the main queue also has <em>user interactive</em> QoS.</p>
<p>To avoid priority inversion in this example, we need to avoid blocking the starter queue with the <code>sync</code> statement. Using <code>async</code> would solve that problem.</p>
<p>Although it’s not always ideal, you can minimize priority inversions by sticking to the default QoS when creating private queues or dispatching to the global concurrent queue.</p>
<h3 id="heading-thread-explosion">Thread explosion</h3>
<p>When you use a concurrent queue, you run the risk of thread explosion if you’re not careful. This can happen when you try to submit tasks to a concurrent queue that is currently blocked (for example with a semaphore, sync, or some other way.) Your tasks <em>will</em> run, but the system will likely end up spinning up new threads to accommodate these new tasks, and threads aren’t cheap.</p>
<p>This is likely why Apple suggests starting with a serial queue per subsystem in your app, as each serial queue can only use one thread. Remember that serial queues are concurrent in relation to <em>other</em> queues, so you still get a performance benefit when you offload your work to a queue, even if it isn’t concurrent.</p>
<h3 id="heading-race-conditions">Race conditions</h3>
<p>Swift Arrays, Dictionaries, Structs, and other value types are not thread-safe by default. For example, when you have multiple threads trying to access and <strong>modify</strong> the same array, you will start running into trouble.</p>
<p>There are different solutions to <a target="_blank" href="https://en.wikipedia.org/wiki/Readers%E2%80%93writers_problem">the readers-writers problem</a>, such as using locks or semaphores. But the relevant solution I wish to discuss here is the use of an <a target="_blank" href="http://khanlou.com/2016/04/the-GCD-handbook/">isolation queue</a>.</p>
<p>Let’s say we have an array of integers, and we want to submit asynchronous work that references this array. As long as our work only <em>reads</em> the array and does not modify it, we are safe. But as soon as we try to modify the array in one of our asynchronous tasks, we will introduce instability in our app.</p>
<p>It’s a tricky problem because your app can run 10 times without issues, and then it crashes on the 11th time. One very handy tool for this situation is the Thread Sanitizer in Xcode. Enabling this option will help you identify potential race conditions in your app.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/01/1-SQpYE8quVN_ziJsg8bqrYQ.png" alt="the thread sanitizer can be accessed in the scheme editor" width="600" height="400" loading="lazy">
<em><strong>t</strong>his option is only available on the simulator<em>**</em></em></p>
<p>To demonstrate the problem, let’s take this (admittedly contrived) example:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ViewController</span>: <span class="hljs-title">UIViewController</span> </span>{

    <span class="hljs-keyword">let</span> concurrent = <span class="hljs-type">DispatchQueue</span>(label: <span class="hljs-string">"com.besher.concurrent"</span>, attributes: .concurrent)
    <span class="hljs-keyword">var</span> array = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>]

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">viewDidLoad</span><span class="hljs-params">()</span></span> {
        <span class="hljs-keyword">for</span> <span class="hljs-number">_</span> <span class="hljs-keyword">in</span> <span class="hljs-number">0</span>...<span class="hljs-number">1</span> {
            race()
        }
    }

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">race</span><span class="hljs-params">()</span></span> {

        concurrent.async {
            <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-keyword">self</span>.array { <span class="hljs-comment">// read access</span>
                <span class="hljs-built_in">print</span>(i)
            }
        }

        concurrent.async {
            <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-number">0</span>..&lt;<span class="hljs-number">10</span> {
                <span class="hljs-keyword">self</span>.array.append(i) <span class="hljs-comment">// write access</span>
            }
        }
    }
}
</code></pre>
<p>One of the <code>async</code> tasks is modifying the array by appending values. If you try running this on your simulator, you might not crash. But run it enough times (or increase the loop frequency on line 7), and you will eventually crash. If you enable the thread sanitizer, you will get a warning every time you run the app.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/01/1-NNBN1ZKViVwYzqJfZenaeQ.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>To deal with this race condition, we are going to add an isolation queue that uses the <a target="_blank" href="https://developer.apple.com/documentation/dispatch/dispatchworkitemflags/1780674-barrier">barrier flag</a>. This flag allows any outstanding tasks on the queue to finish, but blocks any further tasks from executing until the barrier task is completed.</p>
<p>Think of the barrier like a janitor cleaning a public restroom (shared resource.) There are multiple (concurrent) stalls inside the restroom that people can use. </p>
<p>Upon arrival, the janitor places a cleaning sign (barrier) blocking any newcomers from entering until the cleaning is done, but the janitor does not start cleaning until all the people inside have finished their business. Once they all leave, the janitor proceeds to clean the public restroom in isolation. </p>
<p>When finally done, the janitor removes the sign (barrier) so that the people who are queued up outside can finally enter.</p>
<p>Here’s what that looks like in code:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ViewController</span>: <span class="hljs-title">UIViewController</span> </span>{
    <span class="hljs-keyword">let</span> concurrent = <span class="hljs-type">DispatchQueue</span>(label: <span class="hljs-string">"com.besher.concurrent"</span>, attributes: .concurrent)
    <span class="hljs-keyword">let</span> isolation = <span class="hljs-type">DispatchQueue</span>(label: <span class="hljs-string">"com.besher.isolation"</span>, attributes: .concurrent)
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> _array = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>]

    <span class="hljs-keyword">var</span> threadSafeArray: [<span class="hljs-type">Int</span>] {
        <span class="hljs-keyword">get</span> {
            <span class="hljs-keyword">return</span> isolation.sync {
                _array
            }
        }
        <span class="hljs-keyword">set</span> {
            isolation.async(flags: .barrier) {
                <span class="hljs-keyword">self</span>._array = newValue
            }
        }
    }

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">viewDidLoad</span><span class="hljs-params">()</span></span> {
        <span class="hljs-keyword">for</span> <span class="hljs-number">_</span> <span class="hljs-keyword">in</span> <span class="hljs-number">0</span>...<span class="hljs-number">15</span> {
            race()
        }
    }

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">race</span><span class="hljs-params">()</span></span> {
        concurrent.async {
            <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-keyword">self</span>.threadSafeArray {
                <span class="hljs-built_in">print</span>(i)
            }
        }

        concurrent.async {
            <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-number">0</span>..&lt;<span class="hljs-number">10</span> {
                <span class="hljs-keyword">self</span>.threadSafeArray.append(i)
            }
        }
    }
}
</code></pre>
<p>We have added a new isolation queue, and restricted access to the private array using a getter and setter that will place a barrier when modifying the array.</p>
<p>The getter needs to be <code>sync</code> in order to directly return a value. The setter can be <code>async</code>, as we don’t need to block the caller while the write is taking place.</p>
<p>We could have used a serial queue without a barrier to solve the race condition, but then we would lose the advantage of having concurrent read access to the array. Perhaps that makes sense in your case, you get to decide.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Thank you so much for reading this far! I hope you learned something new from this article. I will leave you with a summary and some general advice:</p>
<h3 id="heading-summary">Summary</h3>
<ul>
<li>Queues always <em>start</em> their tasks in FIFO order</li>
<li>Queues are always concurrent relative to <em>other</em> queues</li>
<li><strong>Sync</strong> vs <strong>Async</strong> concerns the source</li>
<li><strong>Serial</strong> vs <strong>Concurrent</strong> concerns the destination</li>
<li>Sync is synonymous with ‘blocking’</li>
<li>Async immediately returns control to caller</li>
<li>Serial uses a single thread, and guarantees order of execution</li>
<li>Concurrent uses multiple-threads, and risks thread explosion</li>
<li>Think about concurrency early in your design cycle</li>
<li>Synchronous code is easier to reason about and debug</li>
<li>Avoid relying on global concurrent queues if possible</li>
<li>Consider starting with a serial queue per subsystem</li>
<li>Switch to concurrent queue only if you see a <strong>measurable</strong> performance benefit</li>
</ul>
<p>I like the metaphor from the <a target="_blank" href="https://gist.github.com/lattner/31ed37682ef1576b16bca1432ea9f782">Swift Concurrency Manifesto</a> of having an ‘island of serialization in a sea of concurrency’. This sentiment was also shared in this tweet by Matt Diephouse:</p>
<div class="embed-wrapper">
        <blockquote class="twitter-tweet">
          <a href="https://twitter.com/mdiep/status/1207112168224763905?s=20"></a>
        </blockquote>
        <script defer="" src="https://platform.twitter.com/widgets.js" charset="utf-8"></script></div>
<p>When you apply concurrency with that philosophy in mind, I think it will help you achieve concurrent code that can be reasoned about without getting lost in a mess of callbacks.</p>
<p>If you have any questions or comments, feel free to reach out to me on <a target="_blank" href="https://twitter.com/BesherMaleh">Twitter</a></p>
<p><a target="_blank" href="https://www.besher.ca">Besher Al Maleh</a></p>
<p>_Cover photo by <a target="_blank" href="https://unsplash.com/@kodozani?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Onur K</a> on <a target="_blank" href="https://unsplash.com/s/photos/railway?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a>_</p>
<h3 id="heading-download-the-companion-app-here">Download the companion app here:</h3>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/almaleh/Dispatcher">https://github.com/almaleh/Dispatcher</a></div>
<h4 id="heading-check-out-some-of-my-other-articles">Check out some of my other articles:</h4>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://medium.com/flawless-app-stories/fireworks-a-visual-particles-editor-for-swift-618e76347798">https://medium.com/flawless-app-stories/fireworks-a-visual-particles-editor-for-swift-618e76347798</a></div>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://medium.com/flawless-app-stories/you-dont-always-need-weak-self-a778bec505ef">https://medium.com/flawless-app-stories/you-dont-always-need-weak-self-a778bec505ef</a></div>
<h4 id="heading-further-reading">Further reading:</h4>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://developer.apple.com/library/archive/documentation/General/Conceptual/ConcurrencyProgrammingGuide/Introduction/Introduction.html">https://developer.apple.com/library/archive/documentation/General/Conceptual/ConcurrencyProgrammingGuide/Introduction/Introduction.html</a></div>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.objc.io/issues/2-concurrency/concurrency-apis-and-pitfalls/#grand-central-dispatch">https://www.objc.io/issues/2-concurrency/concurrency-apis-and-pitfalls/#grand-central-dispatch</a></div>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.objc.io/issues/2-concurrency/low-level-concurrency-apis/">https://www.objc.io/issues/2-concurrency/low-level-concurrency-apis/</a></div>
<p><a target="_blank" href="http://khanlou.com/2016/04/the-GCD-handbook/">http://khanlou.com/2016/04/the-GCD-handbook/</a></p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://stackoverflow.com/a/53582047">https://stackoverflow.com/a/53582047</a></div>
<h4 id="heading-wwdc-videos">WWDC Videos:</h4>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://developer.apple.com/videos/play/wwdc2017/706/">https://developer.apple.com/videos/play/wwdc2017/706/</a></div>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://developer.apple.com/videos/play/wwdc2015/718/">https://developer.apple.com/videos/play/wwdc2015/718/</a></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Concurrency Model and Event Loop ]]>
                </title>
                <description>
                    <![CDATA[ Javascript runtime is single threaded which means that it can execute one piece of code at a time. In order to understand the concurrency model and the event loop in Javascript we have to first get to know some common terms that are associated with i... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-concurrency-model-and-event-loop/</link>
                <guid isPermaLink="false">66c358dbdae03919d93dc098</guid>
                
                    <category>
                        <![CDATA[ concurrency ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 13 Jan 2020 21:46:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9de6740569d1a4ca3a44.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Javascript runtime is single threaded which means that it can execute one piece of code at a time. In order to understand the concurrency model and the event loop in Javascript we have to first get to know some common terms that are associated with it. </p>
<h2 id="heading-the-call-stack">The call stack</h2>
<p>First let’s learn about what a call stack is.</p>
<p>A call stack is a simple data structure that records where in the code we are currently. So if we step into a function that is a function invocation it is pushed to the call stack. When we return from a function it is popped out of the stack.</p>
<p>Let’s look at a code example to understand the call stack:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">multiply</span>(<span class="hljs-params">x,y</span>) </span>{
   <span class="hljs-keyword">return</span> x * y;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">squared</span>(<span class="hljs-params">n</span>) </span>{
     <span class="hljs-keyword">return</span> multiply(n,n)
  }

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printSquare</span>(<span class="hljs-params">n</span>) </span>{
   <span class="hljs-keyword">return</span> squared(n)
}

<span class="hljs-keyword">let</span> numberSquared = printSquare(<span class="hljs-number">5</span>);
<span class="hljs-built_in">console</span>.log(numberSquared);
</code></pre>
<p>First when the code executes the runtime will read through each of the function definitions. But when it reaches the line where the first function <strong>printSquare(5)</strong> is invoked it will push this function into the call stack. </p>
<p>Next, this function will execute. Before returning it will encounter another function, <strong>squared(n)</strong>, so it will suspend its current operation and push this function on top of the existing function. </p>
<p>It executes the function (in this case the squared function) and finally it encounters another function <strong>multiply(n,n)</strong>. Then it suspends its current executions and pushes this function into the call stack. The function multiply executes and it returns with the multiplied value. </p>
<p>Finally the squared function returns and is popped off the stack and then the same goes with printSquare. The final squared value is allocated to the numberSquared variable. </p>
<p>We encounter again a function invocation (in this case it’s a console.log() statement) so the runtime pushes this to the stack. This executes it thus printing the squared number on the console. </p>
<p>Note that the first function that gets pushed into the stack before any of the above code runs is the main function. In the runtime this is denoted as an ‘anonymous function’.</p>
<p>So to summarize: whenever a function is invoked it is pushed into the call stack where it executes. Finally when the function is done with its execution and is returning either implicitly or explicitly it will be popped off the stack. </p>
<p>The call stack just records at what point in time which function was executing. And it keeps track of which function is currently executing.</p>
<h2 id="heading-the-browser">The browser</h2>
<p>Now we know from this that Javascript can execute one thing at a time but that’s not the case with the Browser. The Browser has its own set of APIs like setTimeout and XMLHttpRequests which are not specified in the Javascript runtime. </p>
<p>In fact if you look through the source code of V8, the popular Javascript runtime that powers browsers like Google Chrome, you won’t find any definitions for it. That's because these special web API’s exist in the browser environment not inside the javascript environment. So you can say that these APIs introduce concurrency into the mix. </p>
<p>Let’s look at a diagram to understand the whole picture.</p>
<p><img src="https://i.imgur.com/rnQEY7o.png" alt="Concurrency and Event Loop Model" width="1920" height="1820" loading="lazy"></p>
<p>Some more terms are introduced here, so let's go through them:</p>
<p><strong>Heap</strong>: It’s mostly the place where objects are allocated.</p>
<p><strong>Callback Queue</strong>: It’s a data structure that stores all the callbacks. Since it’s a queue, the elements are processed based on FIFO which is First in First Out.</p>
<p><strong>Event Loop</strong>: This is where all these things come together. The event loop simply checks the call stack, and if it is empty (which means there are no functions in the stack) it takes the oldest callback from the callback queue and pushes it into the call stack which eventually executes the callback.</p>
<p>Let’s understand this with a code example:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">'hi'</span>);

<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
     <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'freecodeCamp'</span>)
},<span class="hljs-number">5000</span>);

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'JS'</span>)
</code></pre>
<p>When the first line executes it’s a console.log(). This is a function invocation which means that this function is pushed into the call stack where it executes printing ‘hi’ to the console. Finally it’s returned and is popped off the stack. </p>
<p>Then when the runtime goes to execute setTimeout() it knows that this is a web API. Therefore it gives it off to the browser to handle its execution. The browser starts the timer and then JS runtime pops the setTimeout() out of the stack. It encounters another console.log() invocation and so it pushes this into the call stack, the message ‘JS’ is logged into the console, and then it’s finally returned. Then the last console.log() is popped off the stack. Now the call stack is empty. </p>
<p>Meanwhile while all of this was going on the timer finishes. When 5 seconds have elapsed the browser goes ahead and pushes the callback function into the callback queue. </p>
<p>Next the event loop checks if the call stack is free or not. Since it is free it takes the callback function and pushes it again back to the call stack which executes the code inside it. </p>
<p>Again inside the code there is a console.log() invocation so this function goes to the top of the stack executes which logs ‘freecodecamp’ into the console and finally it returns. This means it gets popped off the stack and finally the callback gets popped off the stack and we are done.</p>
<p>To visualize this better try this tool by Phillip Roberts: <a target="_blank" href="http://latentflip.com/loupe/?code=!!!PGJ1dHRvbj5DbGljayBtZSE8L2J1dHRvbj4%3D">Loupe Event Loop Visualizer</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Concurrency, parallelism, and the many threads of Santa Claus ? ]]>
                </title>
                <description>
                    <![CDATA[ Consider the following: Santa brings toys to all the good girls and boys. There are 7,713,468,100 people in the world in 2019, around 26.3% of which are under 15 years old. This works out to 2,028,642,110 children (persons under 15 years of age) in t... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/concurrency-parallelism-and-the-many-threads-of-santa-claus/</link>
                <guid isPermaLink="false">66bd8f1effb0fc5947cc911e</guid>
                
                    <category>
                        <![CDATA[ Christmas ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Computer Science ]]>
                    </category>
                
                    <category>
                        <![CDATA[ concurrency ]]>
                    </category>
                
                    <category>
                        <![CDATA[ multithreading ]]>
                    </category>
                
                    <category>
                        <![CDATA[ parallelism ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Threading ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Victoria Drake ]]>
                </dc:creator>
                <pubDate>Tue, 24 Dec 2019 01:18:11 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/12/cover-3.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Consider the following: Santa brings toys to all the good girls and boys.</p>
<p>There are <a target="_blank" href="https://en.wikipedia.org/wiki/Demographics_of_the_world#Current_population_distribution">7,713,468,100 people</a> in the world in 2019, <a target="_blank" href="https://en.wikipedia.org/wiki/Demographics_of_the_world#Age_structure">around 26.3%</a> of which are under 15 years old. This works out to 2,028,642,110 children (persons under 15 years of age) in the world this year.</p>
<p>Santa doesn’t seem to visit children of every religion, so we’ll  generalize and only include Christians and non-religious folks.  Collectively that makes up <a target="_blank" href="https://en.wikipedia.org/wiki/List_of_religious_populations#Adherent_estimates_in_2019">approximately 44.72%</a> of the population. If we assume that all kids take after their parents, then 907,208,751.6 children would appear to be Santa-eligible.</p>
<p>What percentage of those children are good? It’s impossible to know; however, we can work on a few assumptions. One is that Santa Claus functions more on optimism than economics and would likely have prepared  for the possibility that every child is a good child in any given year. Thus, he would be prepared to give a toy to every child. Let’s assume it’s been a great year and that all 907,208,751.6 children are getting toys.</p>
<p>That’s a lot of presents, and, as we know, they’re all made by Santa’s elves at his North China Pole workshop. Given that there are 365 days in a year and one of them  is Christmas, let’s assume that Santa’s elves collectively have 364 days to create and gift wrap 907,208,752 (rounded up) presents. That works out to 2,492,331.74 presents per day.</p>
<p>Almost two-and-a-half million presents per day is a heavy workload for any workshop. Let’s look at two paradigms that Santa might employ to hit this goal: concurrency, and parallelism.</p>
<h2 id="heading-a-sequential-process">A sequential process</h2>
<p>Suppose that Santa’s workshop is staffed by exactly one, very hard working, very tired elf. The production of one present involves four  steps:</p>
<ol>
<li>Cutting wood</li>
<li>Assembly and gluing</li>
<li>Painting</li>
<li>Gift-wrapping</li>
</ol>
<p>With a single elf, only one step for one present can be happening at any instance in time. If the elf were to produce one present at a time from beginning to end, that process would be executed <em>sequentially</em>. It’s not the most efficient method for producing two-and-a-half million presents per day; for instance, the elf would have to wait around doing nothing while the glue on the present was drying before moving on to the next step.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/12/sequence.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-concurrency">Concurrency</h2>
<p>In order to be more efficient, the elf works on all presents <em>concurrently</em>.</p>
<p>Instead of completing one present at a time, the elf first cuts all the wood for all the toys, one by one. When everything is cut, the elf assembles and glues the toys together, one after the other. This <a target="_blank" href="https://en.wikipedia.org/wiki/Concurrent_computing">concurrent processing</a> means that the glue from the first toy has time to dry (without needing more attention from the elf) while the remaining toys are glued together. The same goes for painting, one toy at a time, and finally wrapping.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/12/concurrency.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Since one elf can only do one task at a time, a single elf is using the day as efficiently as possible by concurrently producing presents.</p>
<h2 id="heading-parallelism">Parallelism</h2>
<p>Hopefully, Santa’s workshop has more than just one elf. With more elves, more toys can be built simultaneously over the course of a day. This simultaneous work means that the presents are being produced in <em>parallel</em>. <a target="_blank" href="https://en.wikipedia.org/wiki/Parallel_computing">Parallel processing</a> carried out by multiple elves means more work happens at the same time.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/12/parallel.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Elves working in parallel can also employ concurrency. One elf can still tackle only one task at a time, so it’s most efficient to have multiple elves concurrently producing presents.</p>
<p>Of course, if Santa’s workshop has, say, two-and-a-half million  elves, each elf would only need to finish a maximum of one present per day. In this case, working sequentially doesn’t detract from the workshop’s efficiency. There would still be 7,668.26 elves left over to fetch coffee and lunch.</p>
<h2 id="heading-santa-claus-and-threading">Santa Claus, and threading</h2>
<p>After all the elves’ hard work is done, it’s up to Santa Claus to deliver the presents – all 907,208,752 of them.</p>
<p>Santa doesn’t need to make a visit to every kid; just to the one household tree. So how many trees does Santa need to visit? Again with broad generalization, we’ll say that the average number of children per household worldwide is <a target="_blank" href="https://en.wikipedia.org/wiki/Demographics_of_the_world#Total_fertility_rate">2.45, based on the year’s predicted fertility rates</a>. That makes 370,289,286.4 houses to visit. Let’s round that up to 370,289,287.</p>
<p>How long does Santa have? The lore says one night, which means one earthly rotation, and thus 24 hours. <a target="_blank" href="https://www.noradsanta.org/">NORAD confirms</a>.</p>
<p>This means Santa must visit 370,289,287 households in 24 hours (86,400 seconds), at a rate of 4,285.75 households per second, never mind the time it takes to put presents under the tree and grab a cookie.</p>
<p>Clearly, Santa doesn’t exist in our dimension. This is especially likely given that, despite being chubby and plump, he fits down a chimney (with a lit fire, while remaining unhurt) carrying a sack of toys containing presents for all the household’s children. We haven’t even considered the fact that his sleigh carries enough toys for every believing boy and girl around the world, and flies.</p>
<p>Does Santa exist outside our rules of physics? How could one entity manage to travel around the world, delivering packages, in under 24 hours at a rate of 4,285.75 households per second, and still have time for milk and cookies and kissing mommy?</p>
<p>One thing is certain: Santa uses the Internet. No other technology has yet enabled packages to travel quite so far and quite so quickly. Even so, attempting to reach upwards of four thousand households per second is no small task, even with the best gigabit internet hookup the North Pole has to offer. How might Santa increase his efficiency?</p>
<p>There’s clearly only one logical conclusion to this mystery: Santa Claus is a multithreaded process.</p>
<h2 id="heading-a-single-thread">A single thread</h2>
<p>Let’s work outward. Think of a <a target="_blank" href="https://en.wikipedia.org/wiki/Thread_(computing)">thread</a> as one particular task, or the most granular sequence of instructions that Santa might execute. One thread might execute the task, <code>put present under tree</code>. A thread is a component of a process, in this case, Santa’s process of delivering presents.</p>
<p>If Santa Claus is <a target="_blank" href="https://en.wikipedia.org/wiki/Thread_(computing)#Single_threading">single-threaded</a>, he, as a process, would only be able to accomplish one task at a time. Since he’s old and a bit forgetful, he probably has a set of instructions for delivering presents, as well as a schedule to abide by. These two things guide Santa’s thread until his process is complete.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/12/single.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Single-threaded Santa Claus might work something like this:</p>
<ol>
<li>Land sleigh at Timmy’s house</li>
<li>Get Timmy’s present from sleigh</li>
<li>Enter house via chimney</li>
<li>Locate Christmas tree</li>
<li>Place Timmy’s present under Christmas tree</li>
<li>Exit house via chimney</li>
<li>Take off in sleigh</li>
</ol>
<p>Rinse and repeat… another 370,289,286 times.</p>
<h2 id="heading-multithreading">Multithreading</h2>
<p><a target="_blank" href="https://en.wikipedia.org/wiki/Thread_(computing)#Multithreading">Multithreaded</a> Santa Claus, by contrast, is the <a target="_blank" href="https://dc.fandom.com/wiki/Jonathan_Osterman_(Watchmen)">Doctor Manhattan</a> of the North Pole. There’s still only one Santa Claus in the world; however, he has the amazing ability to multiply his consciousness and accomplish multiple instruction sets of tasks simultaneously. These additional task workers, or worker threads, are created and controlled by the main process of Santa delivering presents.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/12/cover-2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Each worker thread acts independently to complete its instructions. Since they all belong to Santa’s consciousness, they share Santa’s memory and know everything that Santa knows, including what planet they’re running around on, and where to get the presents from.</p>
<p>With this shared knowledge, each thread is able to execute its set of  instructions in parallel with the other threads. This multithreaded  parallelism makes the one and only Santa Claus as efficient as possible.</p>
<p>If an average present delivery run takes an hour, Santa need only spawn 4,286 worker threads. With each making one delivery trip per hour,  Santa will have completed all 370,289,287 trips by the end of the night.</p>
<p>Of course, in theory, Santa could even spawn 370,289,287 worker threads, each flying to one household to deliver presents for all the  children in it! That would make Santa’s process extremely efficient, and also explain how he manages to consume all those milk-dunked cookies without getting full. ????</p>
<h2 id="heading-an-efficient-and-merry-multithreaded-christmas">An efficient and merry multithreaded Christmas</h2>
<p>Thanks to modern computing, we now finally understand how Santa Claus manages the seemingly-impossible task of delivering toys to good girls and boys the world-over. From my family to yours, I hope you have a wonderful Christmas. Don’t forget to hang up your stockings on the router shelf.</p>
<p>Of course, none of this explains how reindeer manage to fly.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Multithreading in Java: How to Get Started with Threads ]]>
                </title>
                <description>
                    <![CDATA[ By Aditya Sridhar What is a Thread? A thread is a lightweight process. Any process can have multiple threads running in it. For example in a web browser, we can have one thread which will load the user interface and another thread which will actually... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-get-started-with-multithreading-in-java/</link>
                <guid isPermaLink="false">66d45d65b3016bf139028d19</guid>
                
                    <category>
                        <![CDATA[ Backend Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ concurrency ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Threading ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 13 Dec 2019 13:45:01 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/12/how-to-get-started-with-multithreading-in-java.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Aditya Sridhar</p>
<h1 id="heading-what-is-a-thread">What is a Thread?</h1>
<p>A thread is a lightweight process. Any process can have multiple threads running in it.</p>
<p>For example in a web browser, we can have one thread which will load the user interface and another thread which will actually retrieve all the data that needs to be displayed in that interface.</p>
<h1 id="heading-what-is-multithreading">What is MultiThreading?</h1>
<p>Multithreading enables us to run multiple threads concurrently.</p>
<p>For example in a web browser, we can have one thread which handles the user interface, and in parallel we can have another thread which fetches the data to be displayed.</p>
<p>So multithreading improves the responsiveness of a system.</p>
<h1 id="heading-what-is-concurrency">What is Concurrency?</h1>
<p>Concurrency in the context of threads enables us to run multiple threads at the same time.</p>
<p>But do the threads really run at the same time?</p>
<h2 id="heading-single-core-systems">Single Core Systems</h2>
<p>The <strong>Thread Scheduler</strong> provided by the JVM decides which thread runs at any given time. The scheduler gives a small time slice to each thread.</p>
<p>So at any given time we have only one thread which is actually running in the processor. But because of the time slicing we get the feeling that multiple threads are running at the same time.</p>
<h2 id="heading-multi-core-systems">Multi Core Systems</h2>
<p>Even in multiple core systems the thread scheduler is involved. But since we have multiple cores, we can actually have multiple threads running at the exact same time.</p>
<p>For example if we have a dual core system, then we can have 2 threads running at the exact same time. The first thread will run in the first core, and the second thread will run in the second core.</p>
<h1 id="heading-why-is-multithreading-needed">Why is Multithreading needed?</h1>
<p>Multithreading enables us to improve the responsiveness of a system.</p>
<p>For example in a web browser, if everything ran in a single thread, then system would be completely unresponsive whenever data was being fetched to display. For example, if it takes 10 seconds to fetch the data, then in that 10 seconds we wont be able to do anything else in the web browser like opening new tabs, or even closing the web browser.</p>
<p>So running different parts of a program in different threads concurrently helps improve the responsiveness of a system.</p>
<h1 id="heading-how-to-write-multithreaded-programs-in-java">How to write Multithreaded Programs in Java</h1>
<p>We can create threads in Java using the following</p>
<ul>
<li>Extending the thread class</li>
<li>Implementing the runnable interface</li>
<li>Implementing the callable interface</li>
<li>By using the executor framework along with runnable and callable tasks</li>
</ul>
<p>We will look at callables and the executor framework in a separate blog. In this article I will be mainly focussing on extending the thread class and implementing the runnable interface.</p>
<h2 id="heading-extending-the-thread-class">Extending the Thread Class</h2>
<p>In order to create a piece of code which can be run in a thread, we create a class and then extend the <strong>thread</strong> class. The task being done by this piece of code needs to be put in the <strong>run()</strong> function. </p>
<p>In the below code you can see that <strong>worker</strong> is a class which extends the <strong>thread</strong> class, and the task of printing numbers 0 to 5 is being done inside the <strong>run()</strong> function.</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Worker</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Thread</span> </span>{

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt;= <span class="hljs-number">5</span>; i++) {
            System.out.println(Thread.currentThread().getName() + <span class="hljs-string">": "</span> + i);
        }
    }

}
</code></pre>
<p>In the above code <strong>Thread.currentThread().getName()</strong> is used to get the name of the current thread which is running the code.</p>
<p>In order to create a <strong>thread</strong>, we just need to create an instance of the worker class. And then we can start the thread using the <strong>start()</strong> function.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ThreadClassDemo</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Thread t1 = <span class="hljs-keyword">new</span> Worker();
        Thread t2 = <span class="hljs-keyword">new</span> Worker();
        Thread t3 = <span class="hljs-keyword">new</span> Worker();
        t1.start();
        t2.start();
        t3.start();

    }
}
</code></pre>
<p>In the above code, we are creating 3 threads (t1,t2 and t3) from the worker class. Then we are starting the threads using the <strong>start()</strong> function.</p>
<p>Here is the final code for creating a thread by extending a thread class:</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Worker</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Thread</span> </span>{

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt;= <span class="hljs-number">5</span>; i++) {
            System.out.println(Thread.currentThread().getName() + <span class="hljs-string">": "</span> + i);
        }
    }

}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ThreadClassDemo</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Thread t1 = <span class="hljs-keyword">new</span> Worker();
        Thread t2 = <span class="hljs-keyword">new</span> Worker();
        Thread t3 = <span class="hljs-keyword">new</span> Worker();
        t1.start();
        t2.start();
        t3.start();

    }
}
</code></pre>
<p>Here is the output we get by running the above code:</p>
<p><img src="https://adityasridhar.com/assets/img/posts/how-to-get-started-with-multithreading-in-java/thread-class-output.png" alt="Thread Class output" width="525" height="295" loading="lazy"></p>
<p>You can see that all the 3 threads have printed the numbers from 0 to 5.</p>
<p><strong>You can also clearly see from the output that the 3 threads do not run in any particular sequence</strong></p>
<h2 id="heading-implementing-the-runnable-interface">Implementing the Runnable Interface</h2>
<p>In order to create a piece of code which can be run in a thread, we create a class and then implement the <strong>runnable</strong> interface. The task being done by this piece of code needs to be put in the <strong>run()</strong> function. </p>
<p>In the below code you can see that <strong>RunnableWorker</strong> is a class which implements <strong>runnable</strong> interface, and the task of printing numbers 0 to 4 is being done inside the <strong>run()</strong> function.</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RunnableWorker</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Runnable</span></span>{

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt;= <span class="hljs-number">4</span>; i++) {
            System.out.println(Thread.currentThread().getName() + <span class="hljs-string">": "</span> + i);
        }
    }

}
</code></pre>
<p>In order to create a thread, first we need to create an Instance of <strong>RunnableWorker</strong> which implements the <strong>runnable</strong> interface.</p>
<p>Then we can create a new thread by creating an instance of the <strong>thread</strong> class and passing the instance of <strong>RunnableWorker</strong> as the argument. This is shown in the code below:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RunnableInterfaceDemo</span> </span>{

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Runnable r = <span class="hljs-keyword">new</span> RunnableWorker();
        Thread t1 = <span class="hljs-keyword">new</span> Thread(r);
        Thread t2 = <span class="hljs-keyword">new</span> Thread(r);
        Thread t3 = <span class="hljs-keyword">new</span> Thread(r);

        t1.start();
        t2.start();
        t3.start();

    }

}
</code></pre>
<p>The above code creates a runnable instance r. Then it create 3 threads (t1, t2 and t3) and passes <strong>r</strong> as the argument to the 3 threads. Then the <strong>start()</strong> function is used to start all 3 threads.</p>
<p>Here is the complete code for creating a thread by implementing the runnable interface:</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RunnableWorker</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Runnable</span></span>{

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt;= <span class="hljs-number">4</span>; i++) {
            System.out.println(Thread.currentThread().getName() + <span class="hljs-string">": "</span> + i);
        }
    }

}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RunnableInterfaceDemo</span> </span>{

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Runnable r = <span class="hljs-keyword">new</span> RunnableWorker();
        Thread t1 = <span class="hljs-keyword">new</span> Thread(r);
        Thread t2 = <span class="hljs-keyword">new</span> Thread(r);
        Thread t3 = <span class="hljs-keyword">new</span> Thread(r);

        t1.start();
        t2.start();
        t3.start();

    }

}
</code></pre>
<p>On running the above code, we will get the following output. The sequence of the output will change every time the code is run.</p>
<p><img src="https://adityasridhar.com/assets/img/posts/how-to-get-started-with-multithreading-in-java/runnable-interface-output.png" alt="Runnable Interface output" width="431" height="242" loading="lazy"></p>
<p><strong>Implementing the runnable interface is a better option than extending the thread class since we can extend only one class, but we can implement multiple interfaces in Java.</strong></p>
<h2 id="heading-runnable-interface-in-java-8">Runnable Interface in Java 8</h2>
<p>In Java 8, the runnable interface becomes a <strong>FunctionalInterface</strong> since it has only one function, <strong>run()</strong>.</p>
<p>The below code shows how we can create a runnable instance in Java 8.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RunnableFunctionalInterfaceDemo</span> </span>{

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{

        Runnable r = () -&gt; {
            <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt;= <span class="hljs-number">4</span>; i++) {
                System.out.println(Thread.currentThread().getName() + <span class="hljs-string">": "</span> + i);
            }
        };

        Thread t1 = <span class="hljs-keyword">new</span> Thread(r);
        Thread t2 = <span class="hljs-keyword">new</span> Thread(r);
        Thread t3 = <span class="hljs-keyword">new</span> Thread(r);

        t1.start();
        t2.start();
        t3.start();
    }

}
</code></pre>
<p>Here, instead of creating a class and then implementing the runnable interface, we can directly use a lambda expression to create a runnable instance as shown below:</p>
<pre><code class="lang-java">Runnable r = () -&gt; {
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt;= <span class="hljs-number">4</span>; i++) {
            System.out.println(Thread.currentThread().getName() + <span class="hljs-string">": "</span> + i);
        }
    };
</code></pre>
<h1 id="heading-code">Code</h1>
<p>The code in this article is available in the following GitHub repo: <a target="_blank" href="https://github.com/aditya-sridhar/basic-threads-demo">https://github.com/aditya-sridhar/basic-threads-demo</a></p>
<h1 id="heading-congrats">Congrats ?</h1>
<p>You now know how to create threads by extending the thread class and by implementing the runnable interface.</p>
<p>I will discuss the thread life cycle and challenges while using threads in my next blog post.</p>
<p><strong>My Website</strong>: <a target="_blank" href="https://adityasridhar.com/">https://adityasridhar.com/</a></p>
<h3 id="heading-feel-free-to-connect-with-me-on-linkedinhttpswwwlinkedincominaditya1811-or-follow-me-on-twitterhttpswwwtwittercomadityasridhar18">Feel free to connect with me on <a target="_blank" href="https://www.linkedin.com/in/aditya1811">LinkedIn</a> or follow me on <a target="_blank" href="https://www.twitter.com/adityasridhar18">Twitter</a></h3>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Code review checklist: how to tackle issues with Java concurrency ]]>
                </title>
                <description>
                    <![CDATA[ By Roman Leventov At the Apache Druid community, we are currently preparing a detailed checklist to be used during code reviews. I decided to publish parts of the checklist as posts on Medium to gather more ideas for checklist items. Hopefully, someb... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/code-review-checklist-java-concurrency-49398c326154/</link>
                <guid isPermaLink="false">66c3476b12c88d894ffd1f48</guid>
                
                    <category>
                        <![CDATA[ code review ]]>
                    </category>
                
                    <category>
                        <![CDATA[ concurrency ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 31 Jan 2019 12:20:31 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*R49yRXvFbFb4kQrfH1eSDg.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Roman Leventov</p>
<p>At the <a target="_blank" href="http://druid.apache.org/">Apache Druid</a> community, we are currently preparing a detailed checklist to be used during code reviews. I decided to publish parts of the checklist as posts on Medium to gather more ideas for checklist items. Hopefully, somebody will find it useful in practice.</p>
<p>By the way, it seems me that creating project-specific checklists for code reviews should be a powerful idea, yet I don’t see any existing examples among large open source projects.</p>
<p>This post contains checklist items about problems that arise with the multithreaded Java code.</p>
<p>Thanks to <a target="_blank" href="https://stackoverflow.com/users/1103872/marko-topolnik">Marko Topolnik</a>, <a target="_blank" href="https://github.com/mmedenjak">Matko Medenjak</a>, <a target="_blank" href="https://github.com/chrisvest">Chris Vest</a>, <a target="_blank" href="https://github.com/s1monw">Simon Willnauer</a>, <a target="_blank" href="https://github.com/ben-manes">Ben Manes</a>, <a target="_blank" href="https://github.com/gvsmirnov">Gleb Smirnov</a>, <a target="_blank" href="https://github.com/asatarin">Andrey Satarin</a>, <a target="_blank" href="https://github.com/asdf2014">Benedict Jin</a>, and <a target="_blank" href="https://stackoverflow.com/users/1273080/petr-jane%C4%8Dek">Petr Janeček</a> for reviews and contributions to this post. The checklist is not considered complete, comments and suggestions are welcome!</p>
<p>Update: this checklist is now available <a target="_blank" href="https://github.com/code-review-checklists/java-concurrency">on Github</a>.</p>
<h4 id="heading-1-design">1. Design</h4>
<p>1.1. If the patch introduces a new subsystem with concurrent code, is <strong>the necessity for concurrency rationalized in the patch description</strong>? Is there a discussion of alternative design approaches that could simplify the concurrency model of the code (see the next item)?</p>
<p>1.2. Is it possible to apply one or several design patterns (some of them are listed below) to significantly <strong>simplify the concurrency model of the code, while not considerably compromising other quality aspects</strong>, such as overall simplicity, efficiency, testability, extensibility, etc?</p>
<p><strong>Immutability/Snapshotting.</strong> When some state should be updated, a new immutable object (or a snapshot within a mutable object) is created, published and used, while some concurrent threads may still use older copies or snapshots. See [EJ Item 17], [JCIP 3.4], items 4.5 and 9.2 in this checklist, <code>CopyOnWriteArrayList</code>, <code>CopyOnWriteArraySet</code>, <a target="_blank" href="https://en.wikipedia.org/wiki/Persistent_data_structure">persistent data structures</a>.</p>
<p><strong>Divide and conquer.</strong> Work is split into several parts that are processed independently, each part in a single thread. Then the results of processing are combined. Parallel Streams (see section 14) or <code>ForkJoinPool</code> (see items 10.4 and 10.5) can be used to apply this pattern.</p>
<p><strong>Producer-consumer.</strong> Pieces of work are transmitted between worker threads via queues. See [JCIP 5.3], item 6.1 in this checklist, <a target="_blank" href="https://en.wikipedia.org/wiki/Communicating_sequential_processes">CSP</a>, <a target="_blank" href="https://en.wikipedia.org/wiki/Staged_event-driven_architecture">SEDA</a>.</p>
<p><strong>Instance confinement.</strong> Objects of some root type encapsulate some complex hierarchical child state. Root objects are solitarily responsible for the safety of accesses and modifications to the child state from multiple threads. In other words, composed objects are synchronized rather than synchronized objects are composed. See [JCIP 4.2, 10.1.3, 10.1.4].</p>
<p><strong>Thread/Task/Serial thread confinement.</strong> Some state is made local to a thread using top-down pass-through parameters or <code>ThreadLocal</code>. See [JCIP 3.3]. Task confinement is a variation of the idea of thread confinement that is used in conjunction with the divide-and-conquer pattern. It usually comes in the form of lambda-captured “context” parameters or fields in the per-thread task objects. Serial thread confinement is an extension of the idea of thread confinement for the producer-consumer pattern, see [JCIP 5.3.2].</p>
<h4 id="heading-2-documentation">2. Documentation</h4>
<p>2.1. For every class, method, and field that has signs of being thread-safe, such as the <code>synchronized</code> keyword, <code>volatile</code> modifiers on fields, use of any classes from <code>java.util.concurrent.*</code>, or third-party concurrency primitives, or concurrent collections: do their Javadoc comments include</p>
<ul>
<li><strong>The justification for thread safety</strong>: is it explained why a particular class, method or field has to be thread-safe?</li>
<li><strong>Concurrent control flow documentation</strong>: is it enumerated from what methods and in contexts of what threads (executors, thread pools) each specific method of a thread-safe class is called?</li>
</ul>
<p>Wherever some logic is parallelized or the execution is delegated to another thread, are there comments explaining why it’s worse or inappropriate to execute the logic sequentially or in the same thread? See also item 14.1 in this checklist about parallel <code>Stream</code> use.</p>
<p>2.2. If the patch introduces a new subsystem that uses threads or thread pools, are there <strong>high-level descriptions of the threading model, the concurrent control flow (or the data flow) of the subsystem</strong> somewhere, e. g. in the Javadoc comment for the package in <code>package-info.java</code> or for the main class of the subsystem? Are these descriptions kept up-to-date when new threads or thread pools are added or some old ones deleted from the system?</p>
<p>Description of the threading model includes the enumeration of threads and thread pools created and managed in the subsystem, and external pools used in the subsystem (such as <code>ForkJoinPool.commonPool()</code>), their sizes and other important characteristics such as thread priorities, and the lifecycle of the managed threads and thread pools.</p>
<p>A high-level description of concurrent control flow should be an overview and tie together concurrent control flow documentation for individual classes, see the previous item. If the producer-consumer pattern is used, the concurrent control flow is trivial and the data flow should be documented instead.</p>
<p>Describing threading models and control/data flow greatly improves the maintainability of the system, because in the absence of descriptions or diagrams developers spend a lot of time and effort to create and refresh these models in their minds. Putting the models down also helps to discover bottlenecks and the ways to simplify the design (see item 1.2).</p>
<p>2.3. For classes and methods that are parts of the public API or the extensions API of the project: is it specified in their Javadoc comments whether they are (or in case of interfaces and abstract classes designed for subclassing in extensions, should they be implemented as) <strong>immutable, thread-safe or not thread-safe</strong>? For classes and methods that are (or should be implemented as) thread-safe, is it documented precisely with what other methods (or themselves) they may be called concurrently from multiple threads? See also [EJ Item 82] and [JCIP 4.5].</p>
<p>If the <code>@com.google.errorprone.annotations.Immutable</code> annotation is used to mark immutable classes, <a target="_blank" href="https://errorprone.info/">Error Prone</a> static analysis tool is capable to detect when a class is not actually immutable (see the relevant <a target="_blank" href="https://errorprone.info/bugpattern/Immutable">bug pattern</a>).</p>
<p>2.4. For subsystems, classes, methods, and fields that use some concurrency design patterns, either high-level (such as those mentioned in item 1.2 in this checklist) or low-level (such as double-checked locking, see section 8 in this checklist): are the used <strong>concurrency patterns pronounced in the design or implementation comments</strong> for the respective subsystems, classes, methods, and fields? This helps readers to make sense out of the code quicker.</p>
<p>2.5. Are <code>ConcurrentHashMap</code> and <code>ConcurrentSkipListMap</code> objects stored in fields and variables of <code>ConcurrentHashMap</code> or <code>ConcurrentSkipListMap</code> or <code>**ConcurrentMap**</code> <strong>type</strong>, but not just <code>Map</code>?</p>
<p>This is important, because in code like the following:</p>
<pre><code>ConcurrentMap&lt;<span class="hljs-built_in">String</span>, Entity&gt; entities = getEntities();<span class="hljs-keyword">if</span> (!entities.containsKey(key)) {  entities.put(key, entity);} <span class="hljs-keyword">else</span> {  ...}
</code></pre><p>It should be pretty obvious that there might be a race condition because an entity may be put into the map by a concurrent thread between the calls to <code>containsKey()</code> and <code>put()</code> (see item 4.1 about this type of race conditions). While if the type of the <code>entities</code> variable was just <code>Map&lt;String, Enti</code>ty&gt; it would be less obvious and readers might think this is only slightly suboptimal code and pass by.</p>
<p>It’s possible to turn this advice into <a target="_blank" href="https://github.com/apache/incubator-druid/pull/6898/files#diff-3aa5d63fbb1f0748c146f88b6f0efc81R239">an inspection</a> in IntelliJ IDEA.</p>
<p>2.6. An extension of the previous item: are ConcurrentHashMaps on which <code>compute()</code>, <code>computeIfAbsent()</code>, <code>computeIfPresent()</code>, or <code>merge()</code> methods are called stored in fields and variables of <code>ConcurrentHashMap</code> type rather than <code>ConcurrentMap</code>? This is because <code>ConcurrentHashMap</code> (unlike the generic <code>ConcurrentMap</code> interface) guarantees that the lambdas passed into <code>compute()</code>-like methods are performed atomically per key, and the thread safety of the class may depend on that guarantee.</p>
<p>This advice may seem to be overly pedantic, but if used in conjunction with a static analysis rule that prohibits calling <code>compute()</code>-like methods on <code>ConcurrentMap</code>-typed objects that are not ConcurrentHashMaps (it’s possible to create such inspection in IntelliJ IDEA too) it could prevent some bugs: e. g. <strong>calling <code>compute()</code> on a <code>ConcurrentSkipListMap</code> might be a race condition</strong> and it’s easy to overlook that for somebody who is used to rely on the strong semantics of <code>compute()</code> in <code>ConcurrentHashMap</code>.</p>
<p>2.7. Is <code>**@GuardedBy**</code> <strong>annotation used</strong>? If accesses to some fields should be protected by some lock, are those fields annotated with <code>@GuardedBy</code>? Are private methods that are called from within critical sections in other methods annotated with <code>@GuardedBy</code>? If the project doesn’t depend on any library containing this annotation (it’s provided by <code>jcip-annotations</code>, <code>error_prone_annotations</code>, <code>jsr305</code> and other libraries) and for some reason it’s undesirable to add such dependency, it should be mentioned in Javadoc comments for the respective fields and methods that accesses and calls to them should be protected by some specified locks.</p>
<p>See [JCIP 2.4] for more information about <code>@GuardedBy</code>.</p>
<p>Using <code>GuardedBy</code> is especially beneficial in together with Error Prone, which is able to <a target="_blank" href="https://errorprone.info/bugpattern/GuardedBy">statically check for unguarded accesses to fields and methods with <code>@GuardedBy</code> annotations</a>.</p>
<p>2.8. If in a thread-safe class some <strong>fields are accessed both from within critical sections and outside of critical sections</strong>, is it explained in comments why this is safe? For example, unprotected read-only access to a reference to an immutable object might be benignly racy (see item 4.5).</p>
<p>2.9. Regarding every field with a <code>volatile</code> modifier: <strong>does it really need to be <code>volatile</code></strong>? Does the Javadoc comment for the field explain why the semantics of <code>volatile</code> field reads and writes (as defined in the <a target="_blank" href="https://docs.oracle.com/javase/specs/jls/se11/html/jls-17.html#jls-17.4">Java Memory Model</a>) are required for the field?</p>
<p>2.10. Is it explained in the <strong>Javadoc comment for each mutable field in a thread-safe class that is neither <code>volatile</code> nor annotated with <code>@GuardedBy</code></strong>, why that is safe? Perhaps, the field is only accessed and mutated from a single method or a set of methods that are specified to be called only from a single thread sequentially (as described in item 2.1). This recommendation also applies to <code>final</code> fields that store objects of non-thread-safe classes when those objects could be mutated from the methods of the enclosing thread-safe class. See items 4.2–4.4 in this checklist about what could go wrong with such code.</p>
<h4 id="heading-3-excessive-thread-safety">3. Excessive thread safety</h4>
<p>3.1. An example of excessive thread safety is a class where every modifiable field is <code>volatile</code> or an <code>AtomicReference</code> or other atomic, and every collection field stores a concurrent collection (e. g. <code>ConcurrentHashMap</code>), although all accesses to those fields are synchronized.</p>
<p><strong>There shouldn’t be any “extra” thread safety in code, there should be just enough of it.</strong> Duplication of thread safety confuses readers because they might think the extra thread safety precautions are (or used to be) needed for something but will fail to find the purpose.</p>
<p>The exception from this principle is the <code>volatile</code> modifier on the lazily initialized field in the <a target="_blank" href="http://hg.openjdk.java.net/code-tools/jcstress/file/9270b927e00f/tests-custom/src/main/java/org/openjdk/jcstress/tests/singletons/SafeLocalDCL.java#l71">safe local double-checked locking pattern</a> which is the recommended way to implement double-checked locking, despite that <code>volatile</code> is <a target="_blank" href="https://shipilev.net/blog/2014/safe-public-construction/#_correctness">excessive for correctness</a> when the lazily initialized object has all <code>final</code> fields<a target="_blank" href="https://shipilev.net/blog/2014/safe-public-construction/#_safe_initialization">*</a>. Without that <code>volatile</code> modifier the thread safety of the double-checked locking could easily be broken by a change (addition of a non-<code>final</code> field) in the class of lazily initialized objects, though that class should not be aware of subtle concurrency implications. If the class of lazily initialized objects is <em>specified</em> to be immutable (see item 2.3) the <code>volatile</code> is still unnecessary and the <a target="_blank" href="http://hg.openjdk.java.net/code-tools/jcstress/file/9270b927e00f/tests-custom/src/main/java/org/openjdk/jcstress/tests/singletons/UnsafeLocalDCL.java#l71">UnsafeLocalDCL</a> pattern could be used safely, but the fact that some class has all <code>final</code> fields doesn’t necessarily mean that it’s immutable.</p>
<p>See also section 8 in this post about double-checked locking.</p>
<p>3.2. Aren’t there <code>**AtomicReference**</code><strong>, <code>AtomicBoolean</code>, <code>AtomicInteger</code> or <code>AtomicLong</code> fields on which only <code>get()</code> and <code>set()</code> methods are called?</strong> Simple fields with <code>volatile</code> modifiers can be used instead, but <code>volatile</code> might not be needed too; see item 2.9.</p>
<h4 id="heading-4-race-conditions">4. Race conditions</h4>
<p>4.1. Aren’t <strong>ConcurrentHashMaps updated with multiple separate <code>containsKey()</code>, <code>get()</code>, <code>put()</code> and <code>remove()</code> calls</strong> instead of a single call to <code>compute()</code>/<code>computeIfAbsent()</code>/<code>computeIfPresent()</code>/<code>replace()</code>?</p>
<p>4.2. Aren’t there <strong>point read accesses such as <code>Map.get()</code>, <code>containsKey()</code> or <code>List.get()</code> outside of critical sections to a non-thread-safe collection such as <code>HashMap</code> or <code>ArrayList</code></strong>, while new entries can be added to the collection concurrently, even though there is a happens-before edge between the moment when some entry is put into the collection and the moment when the same entry is point-queried outside of a critical section?</p>
<p>The problem is that when new entries can be added to a collection, it grows and changes its internal structure from time to time (<code>HashMap</code> rehashes the hash table, <code>ArrayList</code> reallocates the internal array). At such moments races might happen and unprotected point read accesses might fail with <code>NullPointerException</code>, <code>ArrayIndexOutOfBoundsException</code>, or return <code>null</code> or some random entry.</p>
<p>Note that this concern applies to <code>ArrayList</code> even when elements are only added to the end of the list. However, a small change in <code>ArrayList</code>’s implementation in OpenJDK could have disallowed data races in such cases at very little cost. If you are subscribed to the concurrency-interest mailing list, you could help to bring attention to this problem by reviving <a target="_blank" href="http://cs.oswego.edu/pipermail/concurrency-interest/2018-September/016526.html">this thread</a>.</p>
<p>4.3. A variation of the previous item: isn’t a non-thread-safe collection such as <code>HashMap</code> or <code>ArrayList</code> <strong>iterated outside of a critical section</strong>, while it can be modified concurrently? This could happen by accident when an <code>Iterable</code>, <code>Iterator</code> or <code>Stream</code> over a collection is returned from a method of a thread-safe class, even though the iterator or stream is created within a critical section.</p>
<p>Like the previous item, this one applies to growing ArrayLists too.</p>
<p>4.4. More generally, aren’t <strong>non-trivial objects that can be mutated concurrently returned from getters</strong> on a thread-safe class?</p>
<p>4.5. If there are multiple variables in a thread-safe class that are <strong>updated at once but have individual getters</strong>, isn’t there a race condition in the code that calls those getters? If there is, the variables should be made <code>final</code> fields in a dedicated POJO, that serves as a snapshot of the updated state. The POJO is stored in a field of the thread-safe class, directly or as an <code>AtomicReference</code>. Multiple getters to individual fields should be replaced with a single getter that returns the POJO. This allows avoiding a race condition in the client code by reading a consistent snapshot of the state at once.</p>
<p>This pattern is also very useful for crafting safe and reasonably simple non-blocking code: see item 9.2 in this checklist and [JCIP 15.3.1].</p>
<p>4.6. If some logic within some critical section depends on some data that principally is part of the internal mutable state of the class, but was read outside of the critical section or in a different critical section, isn’t there a race condition because the <strong>local copy of the data may become out of sync with the internal state by the time when the critical section is entered</strong>? This is a typical variant of check-then-act race condition, see [JCIP 2.2.1].</p>
<p>4.7. Aren’t there <strong>race conditions between the code (i. e. program runtime actions) and some actions in the outside world</strong> or actions performed by some other programs running on the machine? For example, if some configurations or credentials are hot reloaded from some file or external registry, reading separate configuration parameters or separate credentials (such as username and password) in separate transactions with the file or the registry may be racing with a system operator updating those configurations or credentials.</p>
<p>Another example is checking that a file exists (or not exists) and then reading, deleting, or creating it, respectively, while another program or a user may delete or create the file between the check and the act. It’s not always possible to cope with such race conditions, but it’s useful to keep such possibilities in mind. Prefer static methods from <code>[java.nio.file.Files](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/Files.html)</code> class instead of methods from the old <code>java.io.File</code> for file system operations. Methods from <code>Files</code> are more sensitive to file system race conditions and tend to throw exceptions in adverse cases, while methods on <code>File</code> swallow errors and make it hard even to detect race conditions.</p>
<h4 id="heading-5-replacing-locks-with-concurrency-utilities">5. Replacing locks with concurrency utilities</h4>
<p>5.1. Is it possible to use concurrent collections and/or utilities from <code>java.util.concurrent.*</code> and <strong>avoid using locks with <code>Object.wait()</code>/<code>notify()</code>/<code>notifyAll()</code></strong>? Code redesigned around concurrent collections and utilities is often both clearer and less error-prone than code implementing the equivalent logic with intrinsic locks, <code>Object.wait()</code> and <code>notify()</code> (<code>Lock</code> objects with <code>await()</code> and <code>signal()</code> are not different in this regard). See [EJ Item 81] for more information.</p>
<p>5.2. Is it possible to <strong>simplify code that uses intrinsic locks or <code>Lock</code> objects with conditional waits by using Guava’s <code>[Monitor](https://google.github.io/guava/releases/27.0.1-jre/api/docs/com/google/common/util/concurrent/Monitor.html)</code> instead</strong>?</p>
<h4 id="heading-6-avoiding-deadlocks">6. Avoiding deadlocks</h4>
<p>6.1. If a thread-safe class is implemented so that there are nested critical sections protected by different locks, <strong>is it possible to redesign the code to get rid of nested critical sections</strong>? Sometimes a class could be split into several distinct classes, or some work that is done within a single thread could be split between several threads or tasks which communicate via concurrent queues. See [JCIP 5.3] for more information about the producer-consumer pattern.</p>
<p>6.2. If restructuring a thread-safe class to avoid nested critical sections is not reasonable, was it deliberately checked that the locks are acquired in the same order throughout the code of the class? <strong>Is the locking order documented in the Javadoc comments for the fields where the lock objects are stored?</strong></p>
<p>6.3. If there are nested critical sections protected by several (potentially different) <strong>dynamically determined locks (for example, associated with some business logic entities), are the locks ordered before the acquisition</strong>? See [JCIP 10.1.2] for more information.</p>
<p>6.4. Aren’t there <strong>calls to some callbacks (listeners, etc.) that can be configured through public API or extension interface calls within critical sections</strong> of a class? With such calls, the system might be inherently prone to deadlocks because the external logic executed within a critical section might be unaware of the locking considerations and call back into the logic of the project, where some more locks may be acquired, potentially forming a locking cycle that might lead to deadlock. Let alone the external logic could just perform some time-consuming operation and by that harm the efficiency of the system (see the next item). See [JCIP 10.1.3] and [EJ Item 79] for more information.</p>
<h4 id="heading-7-improving-scalability">7. Improving scalability</h4>
<p>7.1. <strong>Are critical sections as small as possible?</strong> For every critical section: can’t some statements in the beginning and the end of the section be moved out of it? Not only minimizing critical sections improves scalability, but also makes it easier to review them and spot race conditions and deadlocks.</p>
<p>This advice equally applies to lambdas passed into <code>ConcurrentHashMap</code>’s <code>compute()</code>-like methods.</p>
<p>See also [JCIP 11.4.1] and [EJ Item 79].</p>
<p>7.2. Is it possible to <strong>increase locking granularity</strong>? If a thread-safe class encapsulates accesses to map, is it possible to <strong>turn critical sections into lambdas passed into <code>ConcurrentHashMap.compute()</code></strong> or <code>computeIfAbsent()</code> or <code>computeIfPresent()</code> methods to enjoy effective per-key locking granularity? Otherwise, is it possible to use <a target="_blank" href="https://github.com/google/guava/wiki/StripedExplained"><strong>Guava’s <code>Striped</code></strong></a> or an equivalent? See [JCIP 11.4.3] for more information about lock striping.</p>
<p>7.3. Is it possible to <strong>use non-blocking collections instead of blocking ones?</strong> Here are some possible replacements within JDK:</p>
<ul>
<li><code>Collections.synchronizedMap(HashMap)</code>, <code>Hashtable</code> → <code>ConcurrentHashMap</code></li>
<li><code>Collections.synchronizedSet(HashSet)</code> → <code>ConcurrentHashMap.newKeySet()</code></li>
<li><code>Collections.synchronizedMap(TreeMap)</code> → <code>ConcurrentSkipListMap</code>. By the way, <code>ConcurrentSkipListMap</code> is not the state of the art concurrent sorted dictionary implementation. <code>[SnapTree](https://github.com/nbronson/snaptree)</code> is <a target="_blank" href="https://github.com/apache/incubator-druid/pull/6719">more efficient</a> than <code>ConcurrentSkipListMap</code> and there have been some research papers presenting algorithms that are claimed to be more efficient than SnapTree.</li>
<li><code>Collections.synchronizedSet(TreeSet)</code> → <code>ConcurrentSkipListSet</code></li>
<li><code>Collections.synchronizedList(ArrayList)</code>, <code>Vector</code> → <code>CopyOnWriteArrayList</code></li>
<li><code>LinkedBlockingQueue</code> → <code>ConcurrentLinkedQueue</code></li>
<li><code>LinkedBlockingDeque</code> → <code>ConcurrentLinkedDeque</code></li>
</ul>
<p>Was it considered to <strong>use one of the array-based queues from <a target="_blank" href="https://www.baeldung.com/java-concurrency-jc-tools">the JCTools library</a> instead of <code>ArrayBlockingQueue</code></strong>? Those queues from JCTools are classified as blocking, but they avoid lock acquisition in many cases and are generally much faster than <code>ArrayBlockingQueue</code>.</p>
<p>7.4. Is it possible to <strong>use <code>[ClassValue](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/ClassValue.html)</code> instead of <code>ConcurrentHashMap&lt;Class, .</code>.</strong>.&gt;? Note, however, that u<code>nlike ConcurrentH</code>ashMap wit<code>h its computeIfAb</code>sent() m<code>ethod Clas</code>sValue doesn’t guarantee that per-class value is computed only once, <code>i. e. ClassValue.computeV</code>alue() might be executed by multiple concurrent threads. So if the computation i<code>nside computeV</code>alue() is not thread-safe, it should be synchronized separately. On the other <code>hand, Clas</code>sValue does guarantee that the same value is always returned <code>from ClassValue</code>.get() (u<code>nless re</code>move() is called).</p>
<p>7.5. Was it considered to <strong>replace a simple lock with a <code>ReadWriteLock</code></strong>? Beware, however, that it’s more expensive to acquire and release a <code>ReentrantReadWriteLock</code> than a simple intrinsic lock, so the increase in scalability comes at the cost of reduced throughput. If the operations to be performed under a lock are short, or if a lock is already striped (see item 7.2) and therefore very lightly contended, <strong>replacing a simple lock with a <code>ReadWriteLock</code> might have a net negative effect</strong> on the application performance. See <a target="_blank" href="https://medium.com/@leventov/interesting-perspective-thanks-i-didnt-think-about-this-before-e044eec71870">this comment</a> for more details.</p>
<p>7.6. Is it possible to use a <code>[**StampedLock**](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/locks/StampedLock.html)</code> <strong>instead of a <code>ReentrantReadWriteLock</code></strong> when reentrancy is not needed?</p>
<p>7.7. Is it possible to use <code>[**LongAdder**](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/atomic/LongAdder.html)</code> <strong>for “hot fields”</strong> (see [JCIP 11.4.4]) instead of <code>AtomicLong</code> or <code>AtomicInteger</code> on which only methods like <code>incrementAndGet()</code>, <code>decrementAndGet()</code>, <code>addAndGet()</code> and (rarely) <code>get()</code> is called, but not <code>set()</code> and <code>compareAndSet()</code>?</p>
<h4 id="heading-8-lazy-initialization-and-double-checked-locking">8. Lazy initialization and double-checked locking</h4>
<p>8.1. For every lazily initialized field: <strong>is the initialization code thread-safe and might it be called from multiple threads concurrently?</strong> If the answers are “no” and “yes”, either double-checked locking should be used or the initialization should be eager.</p>
<p>8.2. If a field is initialized lazily under a simple lock, is it possible to use double-checked locking instead to improve performance?</p>
<p>8.3. Does double-checked locking follow the <a target="_blank" href="http://hg.openjdk.java.net/code-tools/jcstress/file/9270b927e00f/tests-custom/src/main/java/org/openjdk/jcstress/tests/singletons/SafeLocalDCL.java#l71">SafeLocalDCL</a> pattern, as noted in item 3.1 in this checklist?</p>
<p>If the initialized objects are immutable a more efficient <a target="_blank" href="http://hg.openjdk.java.net/code-tools/jcstress/file/9270b927e00f/tests-custom/src/main/java/org/openjdk/jcstress/tests/singletons/UnsafeLocalDCL.java#l71">UnsafeLocalDCL</a> pattern might also be used. However, if the lazily-initialized field is not <code>volatile</code> and there are accesses to the field that bypass the initialization path, the value of the <strong>field must be carefully cached in a local variable</strong>. For example, the following code is buggy:</p>
<pre><code>private MyClass lazilyInitializedField;
</code></pre><pre><code><span class="hljs-keyword">void</span> foo() {  <span class="hljs-keyword">if</span> (lazilyInitializedField != <span class="hljs-literal">null</span>) { <span class="hljs-comment">// (1)    // Can throw NPE!    lazilyInitializedField.bar();     // (2)  }}</span>
</code></pre><p>It might result in a <code>NullPointerException</code>, because although a non-null value is observed when the field is read the first time at line 1, the second read at line 2 could observe null.</p>
<p>The above code could be fixed as follows:</p>
<pre><code><span class="hljs-keyword">void</span> foo() {  MyClass lazilyInitialized = <span class="hljs-built_in">this</span>.lazilyInitializedField;  <span class="hljs-keyword">if</span> (lazilyInitialized != <span class="hljs-literal">null</span>) {    lazilyInitialized.bar();  }}
</code></pre><p>See “<a target="_blank" href="https://shipilev.net/blog/2016/close-encounters-of-jmm-kind/#wishful-hb-actual">Wishful Thinking: Happens-Before Is The Actual Ordering</a>” for more information.</p>
<p>8.4. In each particular case, doesn’t the <strong>net impact of double-checked locking and lazy field initialization on performance and complexity overweight the benefits of lazy initialization?</strong> Isn’t it ultimately better to initialize the field eagerly?</p>
<p>8.5. If a field is initialized lazily under a simple lock or using double-checked locking, does it really need locking? If nothing bad may happen if two threads do the initialization at the same time and use different copies of the initialized state, a benign race could be allowed. The initialized field should still be <code>volatile</code> (unless the initialized objects are immutable) to ensure there is a happens-before edge between threads doing the initialization and reading the field.</p>
<p>See also [EJ Item 83] and “<a target="_blank" href="https://shipilev.net/blog/2014/safe-public-construction/">Safe Publication this and Safe Initialization in Java</a>”.</p>
<h4 id="heading-9-non-blocking-and-partially-blocking-code">9. Non-blocking and partially blocking code</h4>
<p>9.1. If there is some non-blocking or semi-symmetrically blocking code that mutates the state of a thread-safe class, was it deliberately checked that if a <strong>thread on a non-blocking mutation path is preempted after each statement, the object is still in a valid state</strong>? Are there enough comments, perhaps before almost every statement where the state is changed, to make it relatively easy for readers of the code to repeat and verify the check?</p>
<p>9.2. Is it possible to simplify some non-blocking code by <strong>confining all mutable state in an immutable POJO and update it via compare-and-swap operations</strong>? This pattern is also mentioned in item 4.5. Instead of a POJO, a single <code>long</code> value could be used if all parts of the state are integers that can together fit 64 bits. See also [JCIP 15.3.1].</p>
<h4 id="heading-10-threads-and-executors">10. Threads and Executors</h4>
<p>10.1. <strong>Are Threads given names</strong> when created? Are ExecutorServices created with thread factories that name threads?</p>
<p>It appears that different projects have different policies regarding other aspects of <code>Thread</code> creation: whether to make them daemon with <code>setDaemon()</code>, whether to set thread priorities and whether a <code>ThreadGroup</code> should be specified. Many of such rules can be effectively enforced with <a target="_blank" href="https://github.com/policeman-tools/forbidden-apis">forbidden-apis</a>.</p>
<p>10.2. Aren’t there threads created and started, but not stored in fields, a-la <code>**new Thread(...).start()**</code>, in some methods that may be called repeatedly? Is it possible to delegate the work to a cached or a shared <code>ExecutorService</code> instead?</p>
<p>10.3. <strong>Aren’t some network I/O operations performed in an <code>Executors.newCachedThreadPool()</code>-created <code>ExecutorService</code>?</strong> If a machine that runs the application has network problems or the network bandwidth is exhausted due to increased load, CachedThreadPools that perform network I/O might begin to create new threads uncontrollably.</p>
<p>10.4. <strong>Aren’t there blocking or I/O operations performed in tasks scheduled to a <code>ForkJoinPool</code></strong> (except those performed via a <code>[managedBlock()](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/ForkJoinPool.html#managedBlock(java.util.concurrent.ForkJoinPool.ManagedBlocker))</code> call)? Parallel <code>Stream</code> operations are executed in the common <code>ForkJoinPool</code> implicitly, as well as the lambdas passed into <code>CompletableFuture</code>’s methods whose names end with “Async”.</p>
<p>This advice should not be taken too far: occasional transient IO (such as that may happen during logging) and operations that may rarely block (such as <code>ConcurrentHashMap.put()</code> calls) usually shouldn’t disqualify all their callers from execution in a <code>ForkJoinPool</code> or in a parallel <code>Stream</code>. See <a target="_blank" href="http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html">Parallel Stream Guidance</a> for the more detailed discussion of those tradeoffs.</p>
<p>See also section 14 in this checklist about parallel Streams.</p>
<p>10.5. Opposite of the previous item: <strong>can non-blocking computations be parallelized or executed asynchronously by submitting tasks to <code>ForkJoinPool.commonPool()</code> or via parallel Streams instead of using a custom thread pool</strong> (e. g. created by one of the static factory methods from <code>ExecutorServices</code>)? Unless the custom thread pool is configured with a <code>ThreadFactory</code> that specifies a non-default priority for threads or a custom exception handler (see item 10.1) there is little reason to create more threads in the system instead of reusing threads of the common <code>ForkJoinPool</code>.</p>
<h4 id="heading-11-thread-interruption-and-future-cancellation">11. Thread interruption and <code>Future</code> cancellation</h4>
<p>11.1. If some code propagates <code>InterruptedException</code> wrapped into another exception (e. g. <code>RuntimeException</code>), is <strong>the interruption status of the current thread restored before the wrapping exception is thrown?</strong></p>
<p>Propagating <code>InterruptedException</code> wrapped into another exception is a controversial practice (especially in libraries) and it may be prohibited in some projects completely, or in specific subsystems.</p>
<p>11.2. If some method <strong>returns normally after catching an <code>InterruptedException</code></strong>, is this coherent with the (documented) semantics of the method? Returning normally after catching an <code>InterruptedException</code> usually makes sense only in two types of methods:</p>
<ul>
<li><code>Runnable.run()</code> or <code>Callable.call()</code> themselves, or methods that are intended to be submitted as tasks to some Executors as method references. <code>Thread.currentThread().interrupt()</code> should still be called before returning from the method, assuming that the interruption policy of the threads in the <code>Executor</code> is unknown.</li>
<li>Methods with “try” or “best effort” semantics. Documentation for such methods should be clear that they stop attempting to do something when the thread is interrupted, restore the interruption status of the thread and return.</li>
</ul>
<p>If a method doesn’t fall into either of these categories, it should propagate <code>InterruptedException</code> directly or wrapped into another exception (see the previous item), or it should not return normally after catching an <code>InterruptedException</code>, but rather continue execution in some sort of retry loop, saving the interruption status and restoring it before returning (see an <a target="_blank" href="http://jcip.net/listings/NoncancelableTask.java">example</a> from JCIP). Fortunately, in most situations, it’s not needed to write such boilerplate code: <strong>one of the methods from <code>[Uninterruptibles](https://google.github.io/guava/releases/27.0.1-jre/api/docs/com/google/common/util/concurrent/Uninterruptibles.html)</code> utility class from Guava can be used.</strong></p>
<p>11.3. If an <code>**InterruptedException**</code> <strong>or a <code>TimeoutException</code> is caught on a <code>Future.get()</code> call</strong> and the task behind the future doesn’t have side effects, i. e. <code>get()</code> is called only to obtain and use the result in the context of the current thread rather than achieve some side effect, is the future <a target="_blank" href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/Future.html#cancel(boolean)">canceled</a>?</p>
<p>See [JCIP 7.1] for more information about thread interruption and task cancellation.</p>
<h4 id="heading-12-time">12. Time</h4>
<p>12.1. Are values returned from <code>**System.nanoTime()**</code> <strong>compared in an overflow-aware manner</strong>, as described in <a target="_blank" href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/System.html#nanoTime()">the documentation</a> for this method?</p>
<p>12.2. Does the code that compares values returned from <code>**System.currentTimeMillis()**</code> <strong>have precautions against “time going backward”</strong>? This might happen due to time correction on a server. Values that are returned from <code>currentTimeMillis()</code> that are less than some other values that have already been seen should be ignored. Otherwise, there should be comments explaining why this issue is not relevant for the code.</p>
<p>Alternatively, <code>System.nanoTime()</code> could be used instead of <code>currentTimeMillis()</code>. Values returned from <code>nanoTime()</code> never decrease (but may overflow — see the previous item). Warning: <code>nanoTime()</code> didn’t always uphold to this guarantee in OpenJDK until 8u192 (see <a target="_blank" href="https://bugs.openjdk.java.net/browse/JDK-8184271">JDK-8184271</a>). Make sure to use the freshest distribution.</p>
<p>In distributed systems, the <a target="_blank" href="https://en.wikipedia.org/wiki/Leap_second">leap second</a> adjustment causes similar issues.</p>
<p>12.3. Do <strong>variables that store time limits and periods have suffixes identifying their units</strong>, for example, “timeoutMillis” (also -Seconds, -Micros, -Nanos) rather than just “timeout”? In method and constructor parameters, an alternative is providing a <code>[TimeUnit](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/TimeUnit.html)</code> parameter next to a “timeout” parameter. This is the preferred option for public APIs.</p>
<p>12.4. <strong>Do methods that have “timeout” and “delay” parameters treat negative arguments as zeros?</strong> This is to obey the principle of least astonishment because all timed blocking methods in classes from <code>java.util.concurrent.*</code> follow this convention.</p>
<h4 id="heading-13-thread-safety-of-cleaners-and-native-code">13. Thread safety of Cleaners and native code</h4>
<p>13.1. If a class manages native resources and employs <code>java.lang.ref.Cleaner</code> (or <code>sun.misc.Cleaner</code>; or overrides <code>Object.finalize()</code>) to ensure that resources are freed when objects of the class are garbage collected, and the class implements <code>Closeable</code> with the same cleanup logic executed from <code>close()</code> directly rather than through <code>Cleanable.clean()</code> (or <code>sun.misc.Cleaner.clean()</code>) to be able to distinguish between explicit <code>close()</code> and cleanup through a cleaner (for example, <code>clean()</code> can log a warning about the object not being closed explicitly before freeing the resources), is it ensured that even if the <strong>cleanup logic is called concurrently from multiple threads, the actual cleanup is performed only once</strong>? The cleanup logic in such classes should obviously be idempotent because it’s usually expected to be called twice: the first time from the <code>close()</code> method and the second time from the cleaner or <code>finalize()</code>. The catch is that the cleanup <em>must be concurrently idempotent, even if <code>close()</code> is never called concurrently on objects of the class</em>. That’s because the garbage collector may consider the object to become unreachable before the end of a <code>close()</code> call and initiate cleanup through the cleaner or <code>finalize()</code> while <code>close()</code> is still being executed.</p>
<p>Alternatively, <code>close()</code> could simply delegate to <code>Cleanable.clean()</code> (<code>sun.misc.Cleaner.clean()</code>) which is thread-safe. But then it’s impossible to distinguish between explicit and automatic cleanup.</p>
<p>See also <a target="_blank" href="https://docs.oracle.com/javase/specs/jls/se11/html/jls-12.html#jls-12.6.2">JLS 12.6.2</a>.</p>
<p>13.2. In a class with some native state that has a cleaner or overrides <code>finalize()</code>, are <strong>bodies of all methods that interact with the native state wrapped with</strong><br><strong><code>try { ... } finally { Reference.reachabilityFence(this); }</code></strong>,<br>including constructors and the <code>close()</code> method, but excluding <code>finalize()</code>? This is needed because an object could become unreachable and the native memory might be freed from the cleaner while the method that interacts with the native state is being executed, that might lead to use-after-free or JVM memory corruption.</p>
<p><code>reachabilityFence()</code> in <code>close()</code> also eliminates the race between <code>close()</code> and the cleanup executed through the cleaner or <code>finalize()</code> (see the previous item), but it may be a good idea to retain the thread safety precautions in the cleanup procedure, especially if the class in question belongs to the public API of the project because otherwise if <code>close()</code> is accidentally or maliciously called concurrently from multiple threads, the JVM might crash due to double memory free or, worse, memory might be silently corrupted, while the promise of the Java platform is that whatever buggy some code is, as long as it passes bytecode verification, thrown exceptions should be the worst possible outcome, but the virtual machine shouldn’t crash. Item 13.4 also stresses on this principle.</p>
<p><code>Reference.reachabilityFence()</code> has been added in JDK 9. If the project targets JDK 8 and Hotspot JVM, <a target="_blank" href="http://mail.openjdk.java.net/pipermail/core-libs-dev/2018-February/051312.html">any method with an empty body is an effective emulation of <code>reachabilityFence()</code></a>.</p>
<p>See the documentation for <code>[Reference.reachabilityFence()](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/ref/Reference.html#reachabilityFence(java.lang.Object))</code> and <a target="_blank" href="http://cs.oswego.edu/pipermail/concurrency-interest/2015-December/014609.html">this discussion</a> in the concurrency-interest mailing list for more information.</p>
<p>13.3. Aren’t there classes that have <strong>cleaners or override <code>finalize()</code> not to free native resources</strong>, but merely to return heap objects to some pools, or merely to report that some heap objects are not returned to some pools? This is an antipattern because of the tremendous complexity of using cleaners and <code>finalize()</code> correctly (see the previous two items) and the negative impact on performance (especially of <code>finalize()</code>), that might be even larger than the impact of not returning objects back to some pool and thus slightly increasing the garbage allocation rate in the application. If the latter issue arises to be any important, it should better be diagnosed with <a target="_blank" href="https://github.com/jvm-profiling-tools/async-profiler">async-profiler</a> in the allocation profiling mode (<code>-e alloc</code>) than by registering cleaners or overriding <code>finalize()</code>.</p>
<p>This advice also applies when pooled objects are direct ByteBuffers or other Java wrappers of native memory chunks. <code>[async-profiler -e malloc](https://stackoverflow.com/questions/53576163/interpreting-jemaloc-data-possible-off-heap-leak/53598622#53598622)</code> could be used in such cases to detect direct memory leaks.</p>
<p>13.4. If some <strong>classes have some state in native memory and are used actively in concurrent code, or belong to the public API of the project, was it considered making them thread-safe</strong>? As described in item 13.2, if objects of such classes are inadvertently accessed from multiple threads without proper synchronization, memory corruption and JVM crashes might result. This is why classes in the JDK such as <code>[java.util.zip.Deflater](http://hg.openjdk.java.net/jdk/jdk/file/a772e65727c5/src/java.base/share/classes/java/util/zip/Deflater.java)</code> use synchronization internally despite <code>Deflater</code> objects are not intended to be used concurrently from multiple threads.</p>
<p>Note that making classes with some state in native memory thread-safe also implies that the <strong>native state should be safely published in constructors</strong>. This means that either the native state should be stored exclusively in <code>final</code> fields, or <code>[VarHandle.storeStoreFence()](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/invoke/VarHandle.html#storeStoreFence())</code> should be called in constructors after full initialization of the native state. If the project targets JDK 9 and <code>VarHandle</code> is not available, the same effect could be achieved by wrapping constructors’ bodies in <code>synchronized (this) { ... }</code>.</p>
<h4 id="heading-14-parallel-streams">14. Parallel Streams</h4>
<p>14.1. For every use of parallel Streams via <code>Collection.parallelStream()</code> or <code>Stream.parallel()</code>: <strong>is it explained why parallel <code>Stream</code> is used in a comment preceding the stream operation?</strong> Are there back-of-the-envelope calculations or references to benchmarks showing that the total CPU time cost of the parallelized computation exceeds <a target="_blank" href="http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html">100 microseconds</a>?</p>
<p>Is there a note in the comment that parallelized operations are generally I/O-free and non-blocking, as per item 10.4? The latter might be obvious momentary, but as codebase evolves the logic that is called from the parallel stream operation might become blocking accidentally. Without comment, it’s harder to notice the discrepancy and the fact that the computation is no longer a good fit for parallel Streams. It can be fixed by calling the non-blocking version of the logic again or by using a simple sequential <code>Stream</code> instead of a parallel <code>Stream</code>.</p>
<p>Bonus: is <a target="_blank" href="https://github.com/policeman-tools/forbidden-apis">forbidden-apis</a> configured for the project and are <code>java.util.StringBuffer</code>, <code>java.util.Random</code> and <code>Math.random()</code> prohibited? <code>StringBuffer</code> and <code>Random</code> are thread-safe and all their methods are <code>synchronized</code>, which is never useful in practice and only inhibits the performance. In OpenJDK, <code>Math.random()</code> delegates to a global static <code>Random</code> instance. <code>StringBuilder</code> should be used instead of <code>StringBuffer</code>, <code>ThreadLocalRandom</code> or <code>SplittableRandom</code> should be used instead of <code>Random</code>.</p>
<h3 id="heading-reading-list">Reading List</h3>
<ul>
<li>[JLS] Java Language Specification, <a target="_blank" href="https://docs.oracle.com/javase/specs/jls/se11/html/jls-17.html#jls-17.4">Memory Model</a> and <code>[final](https://docs.oracle.com/javase/specs/jls/se11/html/jls-17.html#jls-17.5)</code> <a target="_blank" href="https://docs.oracle.com/javase/specs/jls/se11/html/jls-17.html#jls-17.5">field semantics</a>.</li>
<li>[EJ] “Effective Java” by Joshua Bloch, Chapter 11. Concurrency.</li>
<li>[JCIP] “Java Concurrency in Practice” by Brian Goetz, Tim Peierls, Joshua Bloch, Joseph Bowbeer, David Holmes, and Doug Lea.</li>
<li>Posts by Aleksey Shipilёv:<br><a target="_blank" href="https://shipilev.net/blog/2014/safe-public-construction/">Safe Publication and Safe Initialization in Java</a><br><a target="_blank" href="https://shipilev.net/blog/2014/jmm-pragmatics/">Java Memory Model Pragmatics</a><br><a target="_blank" href="https://shipilev.net/blog/2016/close-encounters-of-jmm-kind/">Close Encounters of The Java Memory Model Kind</a></li>
<li><a target="_blank" href="http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html">When to use parallel streams</a> written by Doug Lea, with the help of Brian Goetz, Paul Sandoz, Aleksey Shipilev, Heinz Kabutz, Joe Bowbeer, …</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to implement an Object-Pool with an Actor in Kotlin ]]>
                </title>
                <description>
                    <![CDATA[ By osha1 We use object pool in jasync-sql to manage connections to the database. In this post, I will share how it is done in a performant, lock-free manner using Kotlin coroutines with an Actor. An object pool has a very simple API to work with. It ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-implement-an-object-pool-with-an-actor-in-kotlin-ed06d3ba6257/</link>
                <guid isPermaLink="false">66c352b4c2631756f9f063d3</guid>
                
                    <category>
                        <![CDATA[ actor model ]]>
                    </category>
                
                    <category>
                        <![CDATA[ concurrency ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Kotlin ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 09 Nov 2018 19:33:37 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/0*0aDugHie8xlGjhOZ" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By osha1</p>
<p>We use object pool in <a target="_blank" href="https://github.com/jasync-sql/jasync-sql">jasync-sql</a> to manage connections to the database. In this post, I will share how it is done in a performant, lock-free manner using Kotlin coroutines with an Actor.</p>
<p>An object pool has a very simple API to work with. It is a pool of objects with two methods: <code>take()</code> and <code>return()</code>.</p>
<p>On first sight it looks like a very simple problem. The main catch here is that it has to be both performant and thread-safe, and that’s what makes it interesting and tricky to implement.</p>
<h3 id="heading-but-hey-why-do-we-need-an-object-pool-anyway">But hey! Why do we need an object pool anyway?</h3>
<p><a target="_blank" href="https://github.com/jasync-sql/jasync-sql">jasync-sql</a> is a library to access relational databases like MySQL and PostgreSQL. Database connections are a great example of the need for object pools. The access to the database is done by obtaining a connection from a <strong>Connection-Pool</strong>, using it and returning it back to the pool.</p>
<p>With a connection pool we get a couple of advantages over creating connections per each SQL query:</p>
<ul>
<li><em>Reusing connections</em> — since the overhead of initiating a connection to the database is high (handshake, etc), connection pools allow keeping connections alive, thus reducing that overhead.</li>
<li><em>Limiting resources</em> — creating a DB connection per user request can be overwhelming to the DB. Using a pool effectively adds a barrier, limiting the number of maximum number of concurrent connections.</li>
</ul>
<blockquote>
<p>Well, I am sold, but…</p>
</blockquote>
<h3 id="heading-isnt-a-connection-pool-a-solved-problem-in-the-java-world">Isn’t a Connection Pool a solved problem in the Java world?</h3>
<p>Yes it is a solved problem if you’re using <a target="_blank" href="https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/">JDBC</a>. In that case <a target="_blank" href="https://brettwooldridge.github.io/HikariCP/">HikariCP</a> is an excellent choice from my experience, but there are a lot of others. In the case of jasync-sql it is not possible to use <a target="_blank" href="https://brettwooldridge.github.io/HikariCP/">HikariCP</a>, because <a target="_blank" href="https://brettwooldridge.github.io/HikariCP/">HikariCP</a> works with the JDBC API, and the jasync-sql driver is not implementing that full-fledged API, only a subset of it.</p>
<blockquote>
<p>What about other Object pools in Java world?</p>
</blockquote>
<p>There are numerous implementations, but it turns out that you usually find some specific requirement that was not implemented by that pool you’re using.</p>
<p>In our case, that requirement was non-blocking. In our pool, all operations have to be non-blocking since the library is async. For example, the <code>take()</code> operation in most implementations returns an object immediately or blocks until an object is ready. Our <code>take()</code> returns a <code>Future&lt;Connecti</code>on&gt;, which will be completed and continued when the connection is ready to use.</p>
<p>I haven’t seen such an implementation in the wild.</p>
<p>I really like this answer from Stack Exchange:</p>
<p><a target="_blank" href="https://softwareengineering.stackexchange.com/questions/115163/is-object-pooling-a-deprecated-technique"><strong>Is object pooling a deprecated technique?</strong></a><br><a target="_blank" href="https://softwareengineering.stackexchange.com/questions/115163/is-object-pooling-a-deprecated-technique">_Software Engineering Stack Exchange is a question and answer site for professionals, academics, and students working…_softwareengineering.stackexchange.com</a></p>
<p>Another requirement that makes it hard to find an alternative is the need to try and stay compatible as much as possible with the current implementation we have.</p>
<p>In case you want to see other implementations you can check here:</p>
<p><a target="_blank" href="https://www.google.co.il/search?q=object+pool+in+java"><strong>object pool in java - Google Search</strong></a><br><a target="_blank" href="https://www.google.co.il/search?q=object+pool+in+java">_object pool is a collection of a particular object that an application will create and keep on hand for those…_www.google.co.il</a></p>
<h3 id="heading-so-how-did-we-implement-object-pool">So how did we implement Object Pool?</h3>
<p>Before we dive into the details, let’s observe other requirements from the object pool that were omitted above for clarity but are necessary details.</p>
<h4 id="heading-interfaces">Interfaces</h4>
<p>The Object pool interface looks like this:</p>
<pre><code>interface AsyncObjectPool&lt;T&amp;gt; {  fun take(): CompletableFuture&amp;lt;T&gt;  fun giveBack(item: T): CompletableFuture&lt;AsyncObjectPool&lt;T&gt;&gt;  fun close(): CompletableFuture&lt;AsyncObjectPool&lt;T&gt;&gt;
</code></pre><pre><code>}
</code></pre><p>In addition, when a pool wants to create new objects (connections) it will call the <code>ObjectFactory</code>. The factory has a couple more methods to handle the object lifecycle:</p>
<ul>
<li><em>validate</em> — a method to check that the object is still valid. The method should be fast and check only in-memory constructs. For connections we usually check that the last query did not throw an exception and did not get a termination message from <a target="_blank" href="https://netty.io/">netty</a>.</li>
<li><em>test</em> — similar to validate, but a more exhaustive check. We allow test method to be slow and access the network etc. This method is used to check that idle objects are still valid. For connections, that will be something similar to <code>select 0</code>.</li>
<li><em>destroy</em> — called to clean up the object when the pool is not using it anymore.</li>
</ul>
<p>The complete interface is:</p>
<pre><code>interface ObjectFactory&lt;T&gt; {  fun create(): CompletableFuture&lt;;out T&gt;  fun destroy(item: T)  fun validate(item: T): Try&lt;T&gt;  fun test(item: T): CompletableFuture&lt;T&gt;
</code></pre><pre><code>}
</code></pre><p>For pool configuration we have the following properties:</p>
<ul>
<li><code>maxObjects</code> — maximum number of connections we allow.</li>
<li><code>maxIdle</code> — time that we leave the connection open without use. After that time it will be reclaimed.</li>
<li><code>maxQueueSize</code> — when a request for a connection arrives and no connection is available, we put the request on hold in a queue. In case the queue is full (its size passed <code>maxQueueSize</code>) it will not wait but instead return an error.</li>
<li><code>createTimeout</code> — maximum time to wait for a new connection to be created.</li>
<li><code>testTimeout</code> — maximum time to wait for a test query on an idle connection. If it passes we will consider the connection as erroneous.</li>
<li><code>validationInterval</code> — on this interval, we will test if the idle connections are active and free up connections that passed <code>maxIdle</code>. We will also remove connections that passed <code>testTimeout</code>.</li>
</ul>
<h4 id="heading-original-implementation">Original implementation</h4>
<p>The first implementation of object pool was single threaded. All operations were sent to a worker thread that was responsible to execute them. This method is known as <a target="_blank" href="https://www.javaspecialists.eu/archive/Issue218.html">thread-confinement</a>. Object creation and test operations were blocking and query execution itself was non-blocking.</p>
<p>This method is problematic because operations are done one after another. On top of that, there are a couple of operations that are blocking as mentioned above. There were various cases of high latency when working in some scenarios and use cases (like <a target="_blank" href="https://github.com/mauricio/postgresql-async/issues/91">here</a> for example).</p>
<p>As a workaround <code>PartitionedPool</code> was introduced. This is a workaround to the <em>block</em> issue with the above single-threaded approach. The partitioned pool creates multiple <code>SingleThreadedObjectPools</code>, each with its own worker. When a connection is requested, a pool is selected by a modulus on the thread id. The partitioned pool is actually a pool of pools ;-)</p>
<p>I mentioned this is a workaround since it has its own problems: you might still be blocking, but at a lower rate — plus it consume more threads and resources.</p>
<h4 id="heading-actor-based-implementation">Actor based implementation</h4>
<p>An Actor is an entity that has a mailbox. It receives messages to its mailbox and processes them one after the other. The mailbox is a sort of a channel to pass events from the outside world to the actor.</p>
<p>A coroutines actor employs lock-free algorithms to allow fast and performant execution of events without the need for locks and <code>synchronized</code> blocks.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/0*T1B40xs7Fsf-gnfZ" alt="Image" width="800" height="450" loading="lazy">
_“wall rack filled with paper document lot” by [Unsplash](https://unsplash.com/@californong?utm_source=medium&amp;utm_medium=referral" rel="noopener" target="_blank" title=""&gt;Nong Vang on &lt;a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral" rel="noopener" target="<em>blank" title=")</em></p>
<p>You can see an elaborated explanation <a target="_blank" href="https://www.brianstorti.com/the-actor-model/">here</a>.</p>
<p>In our case those events will be <code>take</code> and <code>giveBack</code>. In addition to those, we will have internal messages that the actor sends to itself like <code>objectCreated</code> etc. That allows the actor to have states that does not suffer from concurrency problems, as it is always confined to the same sequential execution. In addition the channel that passes those events is a queue that is using lock-free algorithms so it is very efficient, avoids contention, and generally has very high performance.</p>
<p>There is an excellent video explaining how this was implemented (note that this is “heavy” algorithmic staff):</p>
<p>Let’s recap what we have until now:</p>
<ul>
<li>An actor receives messages and processes them one by one.</li>
<li>Usually messages will contain a <code>CompletableFuture</code> that should be completed when the actor processes it.</li>
</ul>
<p>Messages will be completed immediately or delayed (like in case we are waiting for a connection to be created). If it is delayed the actor will put the <code>Future</code> in a queue, and will use a callback mechanism to notify itself when the original future can be completed.</p>
<ul>
<li>Message processing in the actor should not be blocked or delay the actor. If this happens, it will delay all messages waiting to be processed in the queue and will slow down the entire actor operation.</li>
</ul>
<p><strong>That’s why, in case we have long running operations inside the actor, we use the callback mechanism.</strong></p>
<h4 id="heading-lets-see-more-details-on-the-use-cases">Let’s see more details on the use cases</h4>
<p><code>Take</code> — someone wants an object from the pool. It will send a message with a callback to the actor. The actor will do one of the following things:</p>
<ul>
<li>If the object is available — the actor will simply return it.</li>
<li>If the pool hasn’t passed the limit of created objects — the actor will create a new object and return it when the object is ready.</li>
</ul>
<p>In such a case, object creation can take time, so the actor will connect the callback from the object creation to the original take request callback.</p>
<ul>
<li>Will put the request in a queue for an available object (unless the queue is full and in that case will just return an error).</li>
</ul>
<p><code>GiveBack</code> — someone wants to give an object back to the pool (release it). This is also done by a message to the actor. The actor will do one of the following:</p>
<ul>
<li>If someone is waiting on the wait queue — it will borrow the object to it.</li>
<li>In other cases it will just keep the object on the pool for requests to come, so the object remains idle.</li>
</ul>
<p><code>Test</code> — periodically, someone from outside will notify the actor to test connections:</p>
<ul>
<li>The actor will release the idle connection that hasn’t been used for a long time (it’s configurable).</li>
<li>The actor will test other idle objects using the <code>ObjectFactory</code>. It will send a callback to the factory and mark those objects as <em>In Use</em>, to prevent from borrowing them until the test is completed.</li>
<li>The actor will check for timeouts in tests and destroy time-outed objects.</li>
</ul>
<p>Those are the main use cases.</p>
<h4 id="heading-leaks">Leaks</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/0*64dZ7F9trDtbSdWq" alt="Image" width="800" height="529" loading="lazy">
_“selective focus photography of brown faucet” by [Unsplash](https://unsplash.com/@leipuri?utm_source=medium&amp;utm_medium=referral" rel="noopener" target="_blank" title=""&gt;Jouni Rajala on &lt;a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral" rel="noopener" target="<em>blank" title=")</em></p>
<p>There can be all sort of leaks in an object pool. Some are internal bugs which I hope are easier to spot and fix, and others are objects that were taken but not returned due to some user error. In such cases, objects might remain in the “<em>In Use”</em> queue forever.</p>
<p>To avoid such cases, the <em>“In Use”</em> Map is using Java’s <a target="_blank" href="https://www.baeldung.com/java-weakhashmap">WeakHashMap</a>. So if a user lost a connection it will be automatically removed from the map when it is cleaned by Java’s Garbage-Collector.</p>
<p>In addition we added a log message in such cases that says: <strong>“LEAK-DETECTED”</strong>.</p>
<h3 id="heading-thats-it">That’s it!</h3>
<p>The full Kotlin source code of the object pool is available here:</p>
<p><a target="_blank" href="https://github.com/jasync-sql/jasync-sql/blob/bacdd12243d89a5e2a46501bb5303815a9fd11e7/db-async-common/src/main/java/com/github/jasync/sql/db/pool/ActorBasedObjectPool.kt"><strong>jasync-sql/jasync-sql</strong></a><br><a target="_blank" href="https://github.com/jasync-sql/jasync-sql/blob/bacdd12243d89a5e2a46501bb5303815a9fd11e7/db-async-common/src/main/java/com/github/jasync/sql/db/pool/ActorBasedObjectPool.kt">_Java async database driver for MySQL and PostgreSQL written in Kotlin - jasync-sql/jasync-sql_github.com</a></p>
<p>In an upcoming post I will compare performance metrics of the different implementations.</p>
<p>If you want to read more about Kotlin there is a nice introduction here:</p>
<p>And for coroutines in general check out this video:</p>
<p>Finally if you want to learn more about Actors implementation using coroutines in Kotlin, then head over here:</p>
<p><a target="_blank" href="https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/shared-mutable-state-and-concurrency.md"><strong>Kotlin/kotlinx.coroutines</strong></a><br><a target="_blank" href="https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/shared-mutable-state-and-concurrency.md">_Library support for Kotlin coroutines . Contribute to Kotlin/kotlinx.coroutines development by creating an account on…_github.com</a></p>
<p>Thanks for reading! ❤️</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/0*0aDugHie8xlGjhOZ" alt="Image" width="800" height="599" loading="lazy">
_“aerial photography of woman on pink swimming floats” by [Unsplash](https://unsplash.com/@tom_grimbert?utm_source=medium&amp;utm_medium=referral" rel="noopener" target="_blank" title=""&gt;Tom Grimbert on &lt;a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral" rel="noopener" target="<em>blank" title=")</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Limiting concurrent operations in JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ By Maciej Cieślar Usually, the machine that executes our code has limited resources. Doing everything at once might not only hurt, but can also hang our process and make it stop responding altogether. When we want to crawl 100 websites, we should cra... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-limit-concurrent-operations-in-javascript-b57d7b80d573/</link>
                <guid isPermaLink="false">66d46019e39d8b5612bc0db6</guid>
                
                    <category>
                        <![CDATA[ concurrency ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Productivity ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 28 Aug 2018 20:37:51 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*7F50Qc-ysFgy6tCjUyruTA.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Maciej Cieślar</p>
<p>Usually, the machine that executes our code has limited resources. Doing everything at once might not only hurt, but can also hang our process and make it stop responding altogether.</p>
<p>When we want to crawl 100 websites, we should crawl, for example, 5 at once, so that we don’t take up all the available bandwidth. As soon as one website is crawled, the next one is ready to go.</p>
<p>Generally speaking, all “heavy” operations should be laid out in time. They should not be executed all-at-once, for better performance and to save resources.</p>
<h3 id="heading-implementation">Implementation</h3>
<p>If you are familiar with my previous post about <a target="_blank" href="https://medium.freecodecamp.org/how-to-implement-promises-in-javascript-1ce2680a7f51">implementing promises</a>, then you are going to notice many similarities.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">class</span> Concurrently&lt;T = <span class="hljs-built_in">any</span>&gt; {
  <span class="hljs-keyword">private</span> tasksQueue: (<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">Promise</span>&lt;T&gt;)[] = [];
  <span class="hljs-keyword">private</span> tasksActiveCount: <span class="hljs-built_in">number</span> = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">private</span> tasksLimit: <span class="hljs-built_in">number</span>;

  <span class="hljs-keyword">public</span> <span class="hljs-keyword">constructor</span>(<span class="hljs-params">tasksLimit: <span class="hljs-built_in">number</span></span>) {
    <span class="hljs-keyword">if</span> (tasksLimit &lt; <span class="hljs-number">0</span>) {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Limit cant be lower than 0.'</span>);
    }

    <span class="hljs-built_in">this</span>.tasksLimit = tasksLimit;
  }

  <span class="hljs-keyword">private</span> registerTask(handler) {
    <span class="hljs-built_in">this</span>.tasksQueue = [...this.tasksQueue, handler];
    <span class="hljs-built_in">this</span>.executeTasks();
  }

  <span class="hljs-keyword">private</span> executeTasks() {
    <span class="hljs-keyword">while</span> (<span class="hljs-built_in">this</span>.tasksQueue.length &amp;&amp; <span class="hljs-built_in">this</span>.tasksActiveCount &lt; <span class="hljs-built_in">this</span>.tasksLimit) {
      <span class="hljs-keyword">const</span> task = <span class="hljs-built_in">this</span>.tasksQueue[<span class="hljs-number">0</span>];
      <span class="hljs-built_in">this</span>.tasksQueue = <span class="hljs-built_in">this</span>.tasksQueue.slice(<span class="hljs-number">1</span>);
      <span class="hljs-built_in">this</span>.tasksActiveCount += <span class="hljs-number">1</span>;

      task()
        .then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> {
          <span class="hljs-built_in">this</span>.tasksActiveCount -= <span class="hljs-number">1</span>;
          <span class="hljs-built_in">this</span>.executeTasks();

          <span class="hljs-keyword">return</span> result;
        })
        .catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
          <span class="hljs-built_in">this</span>.tasksActiveCount -= <span class="hljs-number">1</span>;
          <span class="hljs-built_in">this</span>.executeTasks();

          <span class="hljs-keyword">throw</span> err;
        });
    }
  }

  <span class="hljs-keyword">public</span> task(handler: <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">Promise</span>&lt;T&gt;): <span class="hljs-built_in">Promise</span>&lt;T&gt; {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span>
      <span class="hljs-built_in">this</span>.registerTask(<span class="hljs-function">() =&gt;</span>
        handler()
          .then(resolve)
          .catch(reject),
      ),
    );
  }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Concurrently;
</code></pre>
<p>We register a given task by adding it to our <em>tasksQueue</em> and then we call <em>executeTasks</em>.</p>
<p>Now we execute as many tasks as our limit allows us — one by one. Each time adding 1 to our counter called <em>tasksActiveCount</em>.</p>
<p>When the executed task finishes, we remove 1 from <em>tasksActiveCount</em> and again call <em>executeTasks</em>.</p>
<p>Below we can see an example of how it works.</p>
<p>The limit is set to 3. The first two tasks are taking very long to process. We can see the third “slot” getting opened from time to time, allowing the next task in the queue to be executed.</p>
<p>Always there are three, no more, no less.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*MxACL9-7TXYJTpUTQdJIHQ.gif" alt="Image" width="428" height="612" loading="lazy">
<em>Executing heavy and light tasks with the limit of 3.</em></p>
<p>You can see the code in the <a target="_blank" href="https://github.com/maciejcieslar/concurrently">repository</a>.</p>
<p>Thank you very much for reading! Can you think of any other way of achieving the same effect? Share them down below.</p>
<p>If you have any questions or comments feel free to put them in the comment section below or send me a <a target="_blank" href="https://www.mcieslar.com/contact">message</a>.</p>
<p>Check out my <a target="_blank" href="https://www.maciejcieslar.com/about/">social media</a>!</p>
<p><a target="_blank" href="http://eepurl.com/dAKhxb">Join my newsletter</a>!</p>
<p><em>Originally published at <a target="_blank" href="https://www.mcieslar.com/limiting-concurrent-operations-in-javascript">www.mcieslar.com</a> on August 28, 2018.</em></p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
