<?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[ multithreading - 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[ multithreading - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 28 Jun 2026 14:33:12 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/multithreading/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Implement Multi-Threading in Node.js With Worker Threads [Full Handbook] ]]>
                </title>
                <description>
                    <![CDATA[ JavaScript is a single-threaded programming language, and Node.js is the runtime environment for JavaScript. This means that JavaScript essentially runs within Node.js, and all operations are handled through a single thread. But when we perform tasks... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-implement-multi-threading-in-nodejs-with-worker-threads-full-handbook/</link>
                <guid isPermaLink="false">68fba9c10656b6400beb0762</guid>
                
                    <category>
                        <![CDATA[ Node.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ multithreading ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Worker Thread ]]>
                    </category>
                
                    <category>
                        <![CDATA[ workers ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Sumit Saha ]]>
                </dc:creator>
                <pubDate>Fri, 24 Oct 2025 16:30:57 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1761323431527/d74eb2ba-edaa-4d19-a041-364e99a705ba.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>JavaScript is a single-threaded programming language, and Node.js is the runtime environment for JavaScript. This means that JavaScript essentially runs within Node.js, and all operations are handled through a single thread.</p>
<p>But when we perform tasks that require heavy processing, Node.js's performance can start to decline. Many people mistakenly think that Node.js isn’t good or that JavaScript is flawed. But there’s actually a solution. JavaScript can also be used effectively with multi-threading.</p>
<p>In this article, we will focus on the backend: specifically, how to implement multi-threading on the server side using Node.js.</p>
<h2 id="heading-heres-what-well-cover"><strong>Here’s What We’ll Cover</strong></h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-project-setup-with-expressjs">Project Setup with ExpressJS</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-1-create-a-new-project-folder">1. Create a New Project Folder</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-2-initialize-a-nodejs-project">2. Initialize a Node.js Project</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-3-install-expressjs">3. Install Express.js</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-4-optional-install-nodemon-for-development">4. Optional: Install Nodemon for Development</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-5-create-the-main-server-file">5. Create the Main Server File</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-6-run-the-project">6. Run the Project</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-understanding-the-problem">Understanding the Problem</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-observing-the-behavior">Observing the Behavior</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-why-does-this-happen">Why Does This Happen?</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-understanding-javascript-execution">Understanding JavaScript Execution</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-libuv-works">How Libuv Works</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-asynchronous-nature-of-nodejs">Asynchronous Nature of Node.js</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-the-cpu-intensive-problem">The CPU-Intensive Problem</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-implement-worker-threads">How to Implement Worker Threads</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-communication-between-threads">Communication Between Threads</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-setting-up-worker-communication">Setting Up Worker Communication</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-optimize-with-multiple-cores">How to Optimize with Multiple Cores</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-checking-how-many-cores-your-system-has">Checking How Many Cores Your System Has</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-utilizing-multiple-cores-for-faster-execution">Utilizing Multiple Cores for Faster Execution</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-implement-multi-core-optimization">How to Implement Multi-Core Optimization</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-understanding-the-code-line-by-line">Understanding the Code Line by Line</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-thread-planning-and-configuration">Thread Planning and Configuration</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-dividing-work-across-multiple-workers">Dividing Work Across Multiple Workers</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-handling-complex-tasks">Handling Complex Tasks</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-performance-comparison">Performance Comparison</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-testing-results">Testing Results</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-performance-metrics">Performance Metrics</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-key-takeaways">Key Takeaways</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-summary">Summary</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-the-multi-core-challenge">The Multi-Core Challenge</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-discovering-available-cores">Discovering Available Cores</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-asynchronous-worker-creation">Asynchronous Worker Creation</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-multi-threaded-implementation-strategy">Multi-Threaded Implementation Strategy</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-key-concepts-recap">Key Concepts Recap</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-we-learned">What We Learned</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-final-words">Final Words</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-additional-resources">Additional Resources</a></p>
</li>
</ol>
<h2 id="heading-prerequisites"><strong>Prerequisites</strong></h2>
<p>To follow along and get the most out of this guide, you should have:</p>
<ol>
<li><p>Basic JavaScript (ES6-style) knowledge</p>
</li>
<li><p>Familiarity with Node.js fundamentals</p>
</li>
<li><p>Web-server basics using Express (or similar)</p>
</li>
<li><p>Understanding of blocking vs non-blocking operations in Node.js / JavaScript</p>
</li>
<li><p>Comfort with asynchronous code (Promises / async/await) and event-based handling</p>
</li>
<li><p>Setting up a simple development environment with Node.js</p>
</li>
</ol>
<p>I’ve also created a video to go along with this article. If you’re the type who likes to learn from video as well as text, you can check it out here:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/JTl6tQ4bqYA" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<h2 id="heading-project-setup-with-expressjs">Project Setup with ExpressJS</h2>
<p>In this section, we will go through a detailed, beginner-friendly setup for a Node.js project using <a target="_blank" href="https://expressjs.com/">Express</a>. This guide explains every step, so even if you are new to Node.js, you can follow along easily.</p>
<h3 id="heading-1-create-a-new-project-folder">1. Create a New Project Folder</h3>
<p>Start by creating a new folder for your project. Open your terminal or command prompt and run:</p>
<pre><code class="lang-powershell">mkdir node<span class="hljs-literal">-worker</span><span class="hljs-literal">-threads</span>
<span class="hljs-built_in">cd</span> node<span class="hljs-literal">-worker</span><span class="hljs-literal">-threads</span>
</code></pre>
<ul>
<li><p><code>mkdir node-worker-threads</code>: This command creates a new folder named <code>node-worker-threads</code>.</p>
</li>
<li><p><code>cd node-worker-threads</code>: Moves you into the newly created folder where all project files will be stored.</p>
</li>
</ul>
<p>Think of this folder as the home for your project.</p>
<h3 id="heading-2-initialize-a-nodejs-project">2. Initialize a Node.js Project</h3>
<p>Every Node.js project needs a <code>package.json</code> file to manage dependencies and scripts. Run:</p>
<pre><code class="lang-powershell">npm init <span class="hljs-literal">-y</span>
</code></pre>
<ul>
<li><p><code>npm init</code> creates a <code>package.json</code> file.</p>
</li>
<li><p>The <code>-y</code> flag automatically fills in default values, saving you time.</p>
</li>
</ul>
<p>After this, you will see a <code>package.json</code> file in your project folder. This file keeps track of all packages and configurations.</p>
<h3 id="heading-3-install-expressjs">3. Install Express.js</h3>
<p>Express is a lightweight web framework for Node.js. Install it with:</p>
<pre><code class="lang-powershell">npm install express
</code></pre>
<p>This adds Express to your project and allows you to create routes, handle requests, and send responses easily.</p>
<h3 id="heading-4-optional-install-nodemon-for-development">4. Optional: Install Nodemon for Development</h3>
<p>Nodemon automatically restarts your server whenever you make changes. This is very useful during development.</p>
<pre><code class="lang-powershell">npm install <span class="hljs-literal">-D</span> nodemon
</code></pre>
<p>The <code>-D</code> flag installs Nodemon as a development dependency.</p>
<p>Next, Update <code>package.json</code> scripts:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"dev"</span>: <span class="hljs-string">"nodemon index.js"</span>
  }
}
</code></pre>
<p>Now you can start the server with:</p>
<pre><code class="lang-powershell">npm run dev
</code></pre>
<p>This will automatically restart your server whenever you make code changes.</p>
<h3 id="heading-5-create-the-main-server-file">5. Create the Main Server File</h3>
<p>Create a file called <code>index.js</code>. This will be the main entry point of your application:</p>
<pre><code class="lang-powershell">touch index.js
</code></pre>
<p>Open <code>index.js</code> and add the following code:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// index.js </span>

<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>);

<span class="hljs-keyword">const</span> app = express();
<span class="hljs-keyword">const</span> port = process.env.PORT || <span class="hljs-number">3000</span>;

<span class="hljs-comment">// Non-blocking route</span>
app.get(<span class="hljs-string">"/non-blocking"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  res.status(<span class="hljs-number">200</span>).send(<span class="hljs-string">"This page is non-blocking."</span>);
});

<span class="hljs-comment">// Blocking route using Worker Threads</span>
app.get(<span class="hljs-string">"/blocking"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">let</span> result = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">1000000000</span>; i++) {
    result++;
  }
  res.status(<span class="hljs-number">200</span>).send(<span class="hljs-string">`Result is <span class="hljs-subst">${result}</span>`</span>);
});

<span class="hljs-comment">// Start the server</span>
app.listen(port, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`App listening on port <span class="hljs-subst">${port}</span>`</span>);
});
</code></pre>
<p>Here’s what’s going on in this code:</p>
<ul>
<li><p><code>express</code>: To create the server.</p>
</li>
<li><p><code>Worker</code>: To run CPU-intensive tasks in a separate thread.</p>
</li>
<li><p><code>/non-blocking</code> route: Sends a quick response immediately.</p>
</li>
<li><p><code>/blocking</code> route: Runs a Worker thread to handle heavy computation.</p>
</li>
<li><p><code>app.listen</code>: Starts the server on port 3000 (or environment port).</p>
</li>
</ul>
<p>Don’t worry if all of this isn’t perfectly clear at the moment. We’ll explore everything in greater detail as we move forward. Get ready, because we’re going to break down each part step by step in the simplest way possible.</p>
<h3 id="heading-6-run-the-project">6. Run the Project</h3>
<p>Start the server using Nodemon:</p>
<pre><code class="lang-powershell">npm run dev
</code></pre>
<p>Or without Nodemon:</p>
<pre><code class="lang-powershell">node index.js
</code></pre>
<p>Visit these URLs in your browser:</p>
<ul>
<li><p><a target="_blank" href="http://localhost:3000/non-blocking"><code>http://localhost:3000/non-blocking</code></a> displays a simple non-blocking message.</p>
</li>
<li><p><a target="_blank" href="http://localhost:3000/blocking"><code>http://localhost:3000/blocking</code></a> executes a CPU-intensive task using Worker Threads.</p>
</li>
</ul>
<p><strong>Congratulations!</strong> Your Node.js project with Express is fully set up and ready for development.</p>
<h2 id="heading-understanding-the-problem">Understanding the Problem</h2>
<p>We have already set up a basic Express.js application, which is essentially a Node.js app. In this application, we have defined <strong>two routes</strong>:</p>
<ol>
<li><p><code>/non-blocking</code></p>
</li>
<li><p><code>/blocking</code></p>
</li>
</ol>
<p>The <code>/non-blocking</code> route is straightforward: it simply returns a text response saying, "This page is non-blocking."</p>
<p>On the other hand, the <code>/blocking</code> route contains a heavy computation. It runs a loop up to one million numbers, calculates the sum of all these numbers, and then returns the result.</p>
<p>Finally, the application is set to run on port 3000 using <code>app.listen</code>.</p>
<h3 id="heading-observing-the-behavior">Observing the Behavior</h3>
<p>If you open your browser and visit the <a target="_blank" href="http://localhost:3000/non-blocking"><code>http://localhost:3000/non-blocking</code></a> URL, it works perfectly fine and responds immediately.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1761079165626/6d6a3c24-8095-4243-83db-8a44865e5af9.png" alt="Non-blocking Browser" class="image--center mx-auto" width="1920" height="1080" loading="lazy"></p>
<p>But if you visit the <a target="_blank" href="http://localhost:3000/blocking"><code>http://localhost:3000/blocking</code></a> URL, the page keeps loading and doesn’t respond right away.</p>
<p>What's even more interesting is that if you try to access <a target="_blank" href="http://localhost:3000/non-blocking"><code>http://localhost:3000/non-blocking</code></a> <strong>while</strong> <code>/blocking</code> is still running, it also becomes unresponsive.</p>
<p>This demonstrates a key concept: while the <code>/blocking</code> route is executing, even the <code>/non-blocking</code> route cannot respond. In other words, the heavy computation in <code>/blocking</code> <strong>blocks the Node.js event loop</strong>, affecting all other routes.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1761079338040/ecaf458e-d91a-4752-863e-71ac34081949.gif" alt="Blocking Browser" class="image--center mx-auto" width="1138" height="640" loading="lazy"></p>
<h3 id="heading-why-does-this-happen">Why Does This Happen?</h3>
<p>The reason lies in how Node.js works. Node.js is essentially a JavaScript runtime, and as we know, JavaScript is a <strong>single-threaded</strong> programming language. Naturally, Node.js also runs on a single thread by default.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1761079437967/3330b62c-54c2-41a9-bccc-8f962e71287c.gif" alt="Single Threaded Programming" class="image--center mx-auto" width="1138" height="640" loading="lazy"></p>
<p>So, where does the problem arise? When you execute the <code>/blocking</code> route, all the JavaScript code runs on the <strong>main thread</strong>. During this time, the main thread is completely busy or blocked. As a result, if another user tries to access the <code>/non-blocking</code> route, they won't get any response because the main thread is still occupied with the previous task.</p>
<p>This is why many people mistakenly think that JavaScript is weak because it's single-threaded. But this perception is not entirely accurate. With the right approach and techniques, JavaScript <strong>can also be used in a multi-threaded way</strong>, allowing you to handle heavy computations without blocking other operations.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1761079547228/0799f826-3715-4664-b94b-e8f2e80afd04.gif" alt="Weak JS" class="image--center mx-auto" width="1138" height="640" loading="lazy"></p>
<h2 id="heading-understanding-javascript-execution"><strong>Understanding JavaScript Execution</strong></h2>
<p>Let's think about the main thread where JavaScript primarily runs. You might ask, where exactly does JavaScript execute? JavaScript runs inside the <strong>JavaScript engine</strong>, which is responsible for converting JavaScript code into machine code.</p>
<p>In the case of Node.js, it runs on the <strong>V8 engine</strong>, which is the same engine used in Google Chrome. The V8 engine operates entirely on a single thread, meaning all JavaScript code executes within just one main thread.</p>
<p>Now, you might wonder: are there any threads other than the main thread? The answer is yes. Apart from the main thread, there are additional threads used to handle different types of tasks. The management and implementation of these threads are handled by a special library called <strong>Libuv</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1761079628895/02bc21f7-1d49-4952-9c17-3f57cbbe3488.gif" alt="Understanding JavaScript Execution" class="image--center mx-auto" width="1138" height="640" loading="lazy"></p>
<h3 id="heading-how-libuv-works">How Libuv Works</h3>
<p>Libuv is designed to work alongside the V8 Engine. While the V8 Engine executes JavaScript code on the main thread, additional threads are used to handle different types of tasks. For example, operations like database queries, network requests, or file read/write tasks are handled by these extra threads, and the Libuv library manages and coordinates them.</p>
<p>Whenever we perform such tasks, they are actually executed on these extra threads outside the main thread. Libuv instructs the V8 Engine on how to handle these tasks efficiently. These tasks are commonly referred to as <strong>Input/Output operations</strong>, or I/O operations for short. In other words, when performing file read/write, database queries, or network requests, these I/O operations are executed on separate threads without blocking the Main Thread.</p>
<p>But if we have tasks like a large for-loop in our earlier example, or any operation that primarily requires <strong>CPU processing</strong>, they do not fall under I/O operations. In such cases, the task must be executed on the main thread, which inevitably blocks it until the task is completed.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1761079720366/9f01e68c-ad5f-491a-9e68-d91a4ec5f3fb.gif" alt="How libuv works" class="image--center mx-auto" width="1138" height="640" loading="lazy"></p>
<h3 id="heading-asynchronous-nature-of-nodejs"><strong>Asynchronous Nature of Node.js</strong></h3>
<p>Consider a scenario where a client sends a request to the main thread, and this request requires a database query to be executed.</p>
<p>When the user sends such a request, the database query is sent to the database, but importantly, it <strong>does not block</strong> the main thread. Instead, Libuv handles the database query on a <strong>separate thread</strong>, keeping the Main Thread free to handle other tasks.</p>
<p>In this situation, if another user sends a request that does <strong>not</strong> involve any database query or I/O operation, it can be executed immediately on the Main Thread. As a result, this second user receives a response without any delay.</p>
<p>Once the database query running on the separate thread completes, the result is returned to the Main Thread, which then sends it back as a response to the original user. This approach ensures that users receive their output efficiently, and the main thread remains available for other tasks.</p>
<p>This entire process represents the <strong>asynchronous nature</strong> of JavaScript and Node.js. Tasks are not executed synchronously – instead, they run asynchronously. One user's request can be processed on a separate thread while other users continue to interact with the server seamlessly. This is how Node.js maintains high performance and responsiveness even under multiple simultaneous requests.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1761079806477/dd7b58e2-48ab-4994-ad09-41fad2f0b78b.gif" alt="Asynchronous Nature of Node.js" class="image--center mx-auto" width="1138" height="640" loading="lazy"></p>
<h3 id="heading-the-cpu-intensive-problem"><strong>The CPU-Intensive Problem</strong></h3>
<p>So, this is how everything works effectively. Now, the question is, what happens if the main thread has a task that doesn't require any database access for a user's request but demands heavy CPU processing? In that case, the main thread will get blocked.</p>
<p>Let's say a task on the main thread is consuming a lot of CPU. If we execute it directly on the main thread, the event loop will get blocked, and other requests won't be able to be processed.</p>
<p>This is where <strong>worker threads</strong> come into play in Node.js. With worker threads, we can spin up a new thread outside the main thread to handle CPU-heavy operations separately. As a result, the main thread stays free, allowing other requests to be processed immediately.</p>
<p>In other words, by using worker threads, we can run <strong>CPU-bound</strong> tasks <strong>asynchronously</strong>, ensuring that the server's throughput and responsiveness are not affected.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1761079890972/98686661-0c5f-493e-a0b4-25c744c60938.gif" alt="CPU Intensive Problem" class="image--center mx-auto" width="1138" height="640" loading="lazy"></p>
<h2 id="heading-how-to-implement-worker-threads"><strong>How to Implement Worker Threads</strong></h2>
<p>If we take a look at our previous <code>index.js</code> file, the task in the <code>/blocking</code> route handler is running entirely on the main thread, which is why it causes blocking. So, how can we solve this problem? The solution is to use Node.js's built-in worker threads module.</p>
<p>There is <strong>no need to install any external package</strong>, as worker threads is a core module of Node.js.<br>We can directly require the <code>Worker</code> class from the <code>worker_threads</code> module and create a new worker thread.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// index.js</span>

<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>);
<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">const</span> app = express();
<span class="hljs-keyword">const</span> port = process.env.PORT || <span class="hljs-number">3000</span>;

<span class="hljs-comment">// Non-blocking route</span>
app.get(<span class="hljs-string">"/non-blocking"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  res.status(<span class="hljs-number">200</span>).send(<span class="hljs-string">"This page is non-blocking."</span>);
});

<span class="hljs-comment">// Blocking route using Worker Threads</span>
app.get(<span class="hljs-string">"/blocking"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> Worker(<span class="hljs-string">"./worker.js"</span>);

  <span class="hljs-keyword">let</span> result = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">1000000000</span>; i++) {
    result++;
  }
  res.status(<span class="hljs-number">200</span>).send(<span class="hljs-string">`Result is <span class="hljs-subst">${result}</span>`</span>);
});

<span class="hljs-comment">// Start the server</span>
app.listen(port, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`App listening on port <span class="hljs-subst">${port}</span>`</span>);
});
</code></pre>
<p>How it works:</p>
<ul>
<li><p>Inside the <code>/blocking</code> route handler, we create a new worker using <code>new Worker()</code> and provide a file path.</p>
</li>
<li><p>This file (<code>worker.js</code>) contains the <strong>CPU-heavy</strong> task that we want the worker to execute.</p>
</li>
<li><p>For example, our heavy for-loop is moved into this separate file.</p>
</li>
</ul>
<p>We create a new file named <code>worker.js</code> and paste the loop there:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// worker.js</span>

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">1000000000</span>; i++) {
  result++;
}
</code></pre>
<p>When we pass the path to <code>worker.js</code> while creating the Worker, Node.js starts a new thread.</p>
<p>This new thread executes the CPU-intensive task independently, keeping the main thread free to handle other incoming requests.</p>
<p>By doing this, the application becomes more responsive and can handle multiple requests without blocking.</p>
<h3 id="heading-communication-between-threads">Communication Between Threads</h3>
<p>In Node.js, we have the main thread and additional worker threads. To coordinate tasks between them, we can use a <strong>messaging system</strong>. Essentially, all results eventually need to reach the main thread. Otherwise, we won't be able to provide any output to the user.</p>
<p>For example, suppose you assign a task to Thread B and another task to Thread C. When these threads complete their tasks, they must inform the main thread. They do this by sending messages through the messaging system.</p>
<p>Think of it like exchanging messages in an inbox: Thread C sends a message directly to the main thread once its task is finished. Through this communication, worker threads notify the main thread about task completion and send any necessary data.</p>
<p>This is exactly the mechanism we will use in our example to handle CPU-heavy tasks with worker threads, ensuring that the main thread remains free and responsive.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1761079966779/34f22f5e-9334-4e89-b54f-71de3de90923.gif" alt="Communication between threads" class="image--center mx-auto" width="1138" height="640" loading="lazy"></p>
<h3 id="heading-setting-up-worker-communication">Setting Up Worker Communication</h3>
<p>So, we’ve created a <code>worker.js</code> file. Now, the question is, how do we inform the main thread about the task being done in this file?</p>
<p>To achieve this, we extract <code>parentPort</code> from the built-in <code>worker_threads</code> module in Node.js. The <code>parentPort</code> is a special object that allows communication <strong>between the worker thread and the main thread</strong>. It acts as a bridge: whenever the worker completes a task, it can send the result back to the main thread through this channel.</p>
<p>Once the task is complete, we use the method <code>parentPort.postMessage(result)</code> to send the final data. In other words, we’re posting a message to the parent thread, and in our case, that message is the computed result of our loop.</p>
<p>Here’s the full code for the <code>worker.js</code> file:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// worker.js</span>

<span class="hljs-keyword">const</span> { parentPort } = <span class="hljs-built_in">require</span>(<span class="hljs-string">"worker_threads"</span>);

<span class="hljs-keyword">let</span> result = <span class="hljs-number">0</span>;
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10000000000</span>; i++) {
  result++;
}

parentPort.postMessage(result);
</code></pre>
<p>In this example:</p>
<ul>
<li><p>We import parentPort from worker_threads.</p>
</li>
<li><p>We perform a heavy task – a loop that counts up to 10 billion.</p>
</li>
<li><p>After finishing the loop, we send the result back to the main thread using <code>parentPort.postMessage(result)</code>.</p>
</li>
</ul>
<p>This is how communication between the worker thread and the main thread takes place in Node.js.</p>
<p>Now, the question is, once we send the data from the worker, how do we <strong>receive it</strong> in the <code>/blocking</code> handler of our <code>index.js</code> file?</p>
<p>To do this, we need to set up a <strong>listener</strong> inside the handler. For that, we use the <code>worker.on()</code> method.</p>
<p>So, what exactly are we listening for? We listen for the <code>"message"</code> event – just like we listen for <code>onClick</code> or other events in JavaScript.</p>
<p>The first parameter of <code>worker.on()</code> is the event name (<code>"message"</code>), and the second parameter is a <strong>callback function</strong>. Inside that callback, the first argument represents the data we receive from the worker.</p>
<p>Once we receive the data, we can send it back to the browser as a response using:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// index.js </span>

<span class="hljs-comment">// Inside the `/blocking` route handler, we listen for messages from the worker thread.</span>
<span class="hljs-comment">// Whenever the worker completes its task and sends a message, </span>
<span class="hljs-comment">// the callback receives the data as the `data` parameter.</span>
<span class="hljs-comment">// We then send this data back to the client as an HTTP response with status code 200.</span>

worker.on(<span class="hljs-string">"message"</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
  res.status(<span class="hljs-number">200</span>).send(<span class="hljs-string">`Result is <span class="hljs-subst">${data}</span>`</span>);
});
</code></pre>
<p>Explanation<strong>:</strong></p>
<ul>
<li><p><code>worker.on("message", callback)</code> listens for messages sent from the worker thread using <code>parentPort.postMessage()</code>.</p>
</li>
<li><p>The <code>data</code> parameter contains the result sent by the worker.</p>
</li>
<li><p>Using <code>res.status(200).send(...)</code>, we send the computed result back to the browser.</p>
</li>
<li><p>This allows the heavy computation to happen in a separate thread, keeping the main thread free and responsive.</p>
</li>
</ul>
<p>At the same time, we should also handle possible errors.</p>
<p>If any error occurs inside the worker, we can listen for it using the <strong>"error"</strong> event in the same way:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// index.js </span>

<span class="hljs-comment">// In the `/blocking` route handler, we listen for any errors that occur inside the worker thread.</span>
<span class="hljs-comment">// If an error occurs, the callback receives the error object `err`,</span>
<span class="hljs-comment">// and we send it back as an HTTP response with status code 400.</span>

worker.on(<span class="hljs-string">"error"</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
  res.status(<span class="hljs-number">400</span>).send(<span class="hljs-string">`An Error occurred : <span class="hljs-subst">${err}</span>`</span>);
});
</code></pre>
<p>Explanation<strong>:</strong></p>
<ul>
<li><p><code>worker.on("error", callback)</code> listens specifically for errors inside the worker thread.</p>
</li>
<li><p>The <code>err</code> parameter contains details about what went wrong in the worker.</p>
</li>
<li><p>Using <code>res.status(400).send(...)</code>, we return the error to the client so the request doesn’t hang silently.</p>
</li>
</ul>
<p><strong>Here’s how the complete code looks:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// index.js</span>

<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>);
<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">const</span> app = express();
<span class="hljs-keyword">const</span> port = process.env.PORT || <span class="hljs-number">3000</span>;

<span class="hljs-comment">// Non-blocking route</span>
app.get(<span class="hljs-string">"/non-blocking"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  res.status(<span class="hljs-number">200</span>).send(<span class="hljs-string">"This page is non-blocking."</span>);
});

<span class="hljs-comment">// Blocking route using worker threads</span>
app.get(<span class="hljs-string">"/blocking"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> Worker(<span class="hljs-string">"./worker.js"</span>);

  worker.on(<span class="hljs-string">"message"</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
    res.status(<span class="hljs-number">200</span>).send(<span class="hljs-string">`Result is <span class="hljs-subst">${data}</span>`</span>);
  });

  worker.on(<span class="hljs-string">"error"</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
    res.status(<span class="hljs-number">400</span>).send(<span class="hljs-string">`An Error occured : <span class="hljs-subst">${err}</span>`</span>);
  });
});

<span class="hljs-comment">// Start the server</span>
app.listen(port, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`App listening on port <span class="hljs-subst">${port}</span>`</span>);
});
</code></pre>
<p>Once this is set up, you'll see a dramatic change. The <code>/blocking</code> route is loading, but even while it's loading, repeatedly refreshing the <code>/non-blocking</code> route works perfectly without any issues!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1761080061445/f1f213c7-6cce-4334-81e5-8cd828682f8e.gif" alt="Setting up worker communication" class="image--center mx-auto" width="1138" height="640" loading="lazy"></p>
<p>Now notice, the <code>/non-blocking</code> route is accessible, which means even though the <code>/blocking</code> route is still running, it doesn't affect anything. So, we've successfully solved this problem. We moved the main task to a separate thread outside the main thread. What does this mean? The main thread created a new worker thread and assigned the CPU-heavy task to it. The new thread now works independently, while the main thread remains free.</p>
<p>Finally, when the new thread completes its task, it also becomes free. Then, through the messaging system, the new thread informs the main thread, "Your data is ready, here's your data." The main thread receives this data and sends it to the client as a response.</p>
<p>Therefore, the tasks that were automatically handled on separate threads for database queries or file read-write operations – because they were I/O operations – we have now manually initiated a thread and used it to handle similar CPU-heavy tasks.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1761080131679/148cc279-e4f0-4f68-b2a9-34110abcbc90.gif" alt="IO Operations" class="image--center mx-auto" width="1138" height="640" loading="lazy"></p>
<h2 id="heading-how-to-optimize-with-multiple-cores">How to Optimize with Multiple Cores</h2>
<p>Now that you have a clear understanding of how the process works, let's take it one step further and optimize it using multiple CPU cores.</p>
<p>When you visit the <code>/blocking</code> route, you might notice that it still takes a significant amount of time to respond. This indicates that the optimization isn't fully complete yet. So far, we've used a separate thread meaning we've utilized <strong>one CPU core</strong> outside the main thread. But most modern machines have <strong>multiple cores</strong>, and we can take advantage of that to improve performance.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1761080243361/dddd924c-9138-4790-ac6c-811b39772c6c.gif" alt="Final index" class="image--center mx-auto" width="1138" height="640" loading="lazy"></p>
<h3 id="heading-checking-how-many-cores-your-system-has">Checking How Many Cores Your System Has</h3>
<p>Before assigning multiple cores, you can check how many cores are available on your system:</p>
<ul>
<li><p><strong>macOS (Unix-based):</strong></p>
<pre><code class="lang-powershell">  sysctl <span class="hljs-literal">-n</span> hw.ncpu
</code></pre>
<p>  This command returns the total number of CPU cores on your machine. For example, on my Mac, it shows <code>10</code>, meaning I have ten cores available.</p>
</li>
<li><p><strong>Linux:</strong></p>
<pre><code class="lang-powershell">  nproc
</code></pre>
<p>  This will print the number of processing units available.</p>
</li>
<li><p><strong>Windows (Command Prompt):</strong></p>
<pre><code class="lang-powershell">  <span class="hljs-built_in">echo</span> %NUMBER_OF_PROCESSORS%
</code></pre>
</li>
</ul>
<p>Each of these commands will help you determine how many cores you can use for parallel processing.</p>
<h3 id="heading-utilizing-multiple-cores-for-faster-execution">Utilizing Multiple Cores for Faster Execution</h3>
<p>Once you know how many cores your machine has, you can decide how many of them to allocate for a specific job. For example, since my system has ten cores, I might choose to use four cores for the task.</p>
<p>By distributing the workload across multiple threads (each running on its own core), you can achieve significant performance improvements. Instead of relying on just one core, the system can execute multiple parts of the task simultaneously reducing the total execution time dramatically.</p>
<p>In short, the more cores you effectively utilize, the faster your computationally heavy tasks can complete (as long as your code is designed to handle parallel execution safely).</p>
<h2 id="heading-how-to-implement-multi-core-optimization">How to Implement Multi-Core Optimization</h2>
<p>Now, we'll optimize the <code>/blocking</code> task by using multiple worker threads. First, we’ll create copies of our existing files:</p>
<ul>
<li><p><code>index.js</code> → <code>index-optimized.js</code></p>
</li>
<li><p><code>worker.js</code> → <code>worker-optimized.js</code></p>
</li>
</ul>
<p>We plan to use four threads. Even though the machine may have more cores, using all could overload the system, so we’ll limit it to four.</p>
<p><strong>index-optimize.js:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// index-optimize.js</span>

<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>);
<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">const</span> app = express();
<span class="hljs-keyword">const</span> port = process.env.PORT || <span class="hljs-number">3000</span>;
<span class="hljs-keyword">const</span> THREAD_COUNT = <span class="hljs-number">4</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createWorker</span>(<span class="hljs-params"></span>) </span>{
    <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-keyword">const</span> worker = <span class="hljs-keyword">new</span> Worker(<span class="hljs-string">"./worker-optimized.js"</span>, {
            <span class="hljs-attr">workerData</span>: {
                <span class="hljs-attr">thread_count</span>: THREAD_COUNT,
            },
        });

        worker.on(<span class="hljs-string">"message"</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
            resolve(data);
        });

        worker.on(<span class="hljs-string">"error"</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
            reject(<span class="hljs-string">`An Error occured : <span class="hljs-subst">${err}</span>`</span>);
        });
    });
}

app.get(<span class="hljs-string">"/non-blocking"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    res.status(<span class="hljs-number">200</span>).send(<span class="hljs-string">"This page is non-blocking."</span>);
});

app.get(<span class="hljs-string">"/blocking"</span>, <span class="hljs-keyword">async</span> (req, res) =&gt; {
    <span class="hljs-keyword">const</span> workerPromise = [];

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; THREAD_COUNT; i++) {
        workerPromise.push(createWorker());
    }

    <span class="hljs-keyword">const</span> threadResults = <span class="hljs-keyword">await</span> <span class="hljs-built_in">Promise</span>.all(workerPromise);
    <span class="hljs-keyword">const</span> total =
        threadResults[<span class="hljs-number">0</span>] +
        threadResults[<span class="hljs-number">1</span>] +
        threadResults[<span class="hljs-number">2</span>] +
        threadResults[<span class="hljs-number">3</span>];

    res.status(<span class="hljs-number">200</span>).send(<span class="hljs-string">`Result is <span class="hljs-subst">${total}</span>`</span>);
});

app.listen(port, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`App listening on port <span class="hljs-subst">${port}</span>`</span>);
});
</code></pre>
<p>Here, we create a <code>createWorker</code> function that returns a Promise. Inside it, the worker is created, and the message and error events are handled. In the <code>/blocking</code> route, we create multiple workers asynchronously, wait for all of them to finish using <code>Promise.all</code>, and then sum the results.</p>
<p><strong>worker-optimize.js:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// worker-optimize.js</span>

<span class="hljs-keyword">const</span> { parentPort, workerData } = <span class="hljs-built_in">require</span>(<span class="hljs-string">"worker_threads"</span>);

<span class="hljs-keyword">let</span> result = <span class="hljs-number">0</span>;
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10000000000</span> / workerData.thread_count; i++) {
    result++;
}

parentPort.postMessage(result);
</code></pre>
<p>Each worker receives <code>thread_count</code> from the main thread and calculates its part of the task. Once done, it sends the result back using <code>parentPort.postMessage</code>. This way, heavy computation is distributed, and the main thread remains free.</p>
<h3 id="heading-understanding-the-code-line-by-line">Understanding the Code Line by Line</h3>
<p>Alright, some of these concepts might seem a bit complex at first. But don't worry! We we’ll go through all the code line by line, explaining everything in detail so that you understand exactly what is happening and why.</p>
<h3 id="heading-thread-planning-and-configuration">Thread Planning and Configuration</h3>
<p>Now, coming to the main point we'll be using threads, right? We've planned to use multiple threads. Let's say we've decided to use four threads. Our machine has ten cores, but we won't use them all because that would consume all our system resources. So, we'll use four threads from four of the available cores.</p>
<p>For this reason, in the <code>index-optimized.js</code> file, we've created a constant to store the number of threads we'll use. Let's say we've set it to 4 here, so that later another developer can easily change it if needed.</p>
<h4 id="heading-the-createworker-function">The createWorker Function</h4>
<p>Then, we've created a new function called <code>createWorker</code>. The purpose of this function is to create a new Worker. Here, we’re returning a promise because the process of creating a Worker is performed asynchronously.</p>
<p>This is because when we create four workers, we want the creation process itself to happen asynchronously, so the main thread doesn't get blocked. After all, creating a worker is essentially a separate process.</p>
<p>The best practice is to create workers asynchronously. That's why we created the <code>createWorker</code> function, which returns a promise. As we know, events are listened to inside a promise, where resolve and reject are used. In the <code>/blocking</code> handler, we can handle the worker's result or any errors through this promise.</p>
<h4 id="heading-creating-a-worker">Creating a Worker</h4>
<p>To create a worker, we use:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> Worker(<span class="hljs-string">"./worker-optimized.js"</span>);
</code></pre>
<p>Here, we need to provide the path to the Worker file. Then, as the second parameter, we can pass some options. For example, if we want to send some data to the Worker, we use <code>{ workerData }</code>. Inside this <code>workerData</code>, we'll send the <code>THREAD_COUNT</code>, which is stored in our file as <code>THREAD_COUNT</code>.</p>
<p>For instance, we can pass an object in <code>workerData</code> like:</p>
<pre><code class="lang-javascript">{
  <span class="hljs-attr">threadCount</span>: THREAD_COUNT;
}
</code></pre>
<p>When this Worker is being created, we send some properties from <code>index-optimized.js</code> as <code>workerData</code>. This is because in <code>worker-optimized.js</code>, the worker can use <code>parentPort</code> to know how many threads it should use. So, we've included a <code>threadCount</code> property in <code>workerData</code>. When the worker starts, it reads <code>threadCount</code> from <code>workerData</code> and works accordingly. This is how we've designed the <code>createWorker</code> function, which simply returns a Promise.</p>
<h4 id="heading-event-handling-and-promise-structure">Event Handling and Promise Structure</h4>
<p>Here, we made an important change compared to our original <code>index.js</code> file.</p>
<p>Since we copied all the code from <code>index.js</code> into <code>index-optimized.js</code>, we adjusted the <code>/blocking</code> route handler. Specifically, we removed the direct creation of the Worker from the <code>/blocking</code> handler. Instead, the Worker is now created inside the <code>createWorker</code> function.</p>
<p>Also, all the event listeners (<code>message</code> and <code>error</code>) that were previously inside the <code>/blocking</code> handler have also been moved into the <code>createWorker</code> function. This means that the worker is fully managed within the function, and the <code>/blocking</code> handler now only handles the promise results, keeping the main thread clean and organized.</p>
<p>But since these events are being listened to inside a promise, we cannot send the response directly from there. We'll send the response inside the <code>/blocking</code> handler. So from the Promise, we only use <code>resolve</code> and <code>reject</code>.</p>
<p><strong>For example:</strong></p>
<pre><code class="lang-javascript">resolve(<span class="hljs-string">`Result is <span class="hljs-subst">${data}</span>`</span>);
reject(<span class="hljs-string">`An error occurred <span class="hljs-subst">${err}</span>`</span>);
</code></pre>
<p>In other words, the entire process of creating a worker has been moved into the <code>createWorker</code> function, which ultimately returns a promise.</p>
<h3 id="heading-dividing-work-across-multiple-workers">Dividing Work Across Multiple Workers</h3>
<p>Now, inside the <code>/blocking</code> handler, I simply call the <code>createWorker</code> function. The workerData we provide tells the worker what task it should perform. The created worker is linked with parentPort in the <code>worker-optimized.js</code> file, which essentially communicates with the parent thread.</p>
<p>Now, we want to divide the for-loop running up to one million across four cores. The number of cores to use is sent from <code>index-optimized.js</code> as part of workerData. Because this information is in workerData, the workers can automatically divide and handle the tasks among themselves.</p>
<p>So, in the <code>worker-optimized.js</code> file, we'll get the workerData using:</p>
<pre><code class="lang-javascript">{ workerData } = <span class="hljs-built_in">require</span>(<span class="hljs-string">"worker_threads"</span>)
</code></pre>
<p>Then, in the for-loop condition, we'll use <code>workerData.threadCount</code>. This means the threadCount sent from <code>index-optimized.js</code> will be used here instead of hardcoding 4. This is best practice because the data is passed to the worker at the time of its creation. In <code>worker-optimized.js</code>, we use this to divide the work into four parts. Then, four workers will be created, meaning the <code>createWorker</code> function will be called four times. Each worker will take one part of the work, and at the end, all results will be combined. This is how the entire process is completed.</p>
<p>So, in this <code>/blocking</code> handler, our task is to collect the results of the four promises and then sum them all. Let's say we store them in an array called <code>workerPromises</code>. Each entry in this array will hold the promise result of a worker. Then, by combining all of them, we get the final result.</p>
<p>Since we need to create four Workers, we'll run a for-loop: <code>for (let i = 0; i &lt; THREAD_COUNT; i++)</code>. Inside the body of this loop, we'll call the <code>createWorker</code> function each time. This means that in every iteration, a new worker is created, and its promise is pushed into the <code>workerPromises</code> array.</p>
<p>So, inside the body of this loop, we'll call the <code>createWorker</code> function four times. Each call to <code>createWorker</code> returns a promise. These four promises are pushed into the <code>workerPromises</code> array, like <code>workerPromises.push(createWorker())</code>. This way, each worker has its own promise. In the end, since all the promises are stored in the <code>workerPromises</code> array, we can easily call <code>Promise.all(workerPromises)</code>.</p>
<p>So, we used <code>threadResults = await Promise.all(workerPromises)</code>. As we know, <code>Promise.all</code> can handle multiple Promises together. Here, we passed the <code>workerPromises</code> array, so <code>threadResults</code> will contain the results of the four promises as separate elements, like <code>threadResults[0]</code>, <code>threadResults[1]</code>, <code>threadResults[2]</code>, and <code>threadResults[3]</code>. Then, we sum these results to get the total calculation, meaning <code>threadResults[0] + threadResults[1] + threadResults[2] + threadResults[3]</code> gives the final result. Since we used await, the entire function needs to be async.</p>
<p>Once everything is done correctly, we can send this total result to the client using <code>res.status(200).send(Result is ${total})</code>. This way, the total calculation works correctly, unlike before.</p>
<p>So, I hope it's clear now: we called the <code>createWorker</code> function four times here. Each call returns a promise. We then awaited all these promises together using <code>Promise.all</code>, so all the results came in at once. After that, we summed these results. The <code>/blocking</code> handler is essentially the one executing our operational work.</p>
<h3 id="heading-handling-complex-tasks">Handling Complex Tasks</h3>
<p>So, in the <code>worker-optimized.js</code> file, we've essentially divided the work into four parts. But it's not necessary that the task will always be a for-loop. There could be different types of complex tasks as well, like image processing, data processing, or pagination.</p>
<p>In such cases, we can't always follow the same pattern. So, we need to send the necessary data from <code>index-optimized.js</code> as <code>workerData</code>, and the worker will use that data to perform the task in a separate process.</p>
<p>In the previous example, all the steps were sequential, so simply summing the results gave us the total. But in the case of complex tasks, we need to use data-driven processing.</p>
<p>In other complex applications, you might need to perform different tasks. But the main concept is clear: any data or property we send from here will be received by the worker, which will then divide the work. Each worker – whether you use four, five, or six – will handle its part, and all the results will need to be accumulated. This is essentially the entire process.</p>
<h2 id="heading-performance-comparison"><strong>Performance Comparison</strong></h2>
<p>When working with CPU-intensive tasks in Node.js, dividing the work using worker threads can significantly improve performance. Let's compare the behavior of our application before and after optimization.</p>
<h3 id="heading-testing-results">Testing Results</h3>
<p>Running the <code>index.js</code> file and hitting the <code>/blocking</code> route in the browser takes a significant amount of time.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1761164273474/02892dd3-3524-4e7e-83fa-ac279910d759.gif" alt="Final Index" class="image--center mx-auto" width="1138" height="640" loading="lazy"></p>
<p>Running the <code>index-optimized.js</code> file and hitting the same route takes considerably less time – around 3 seconds.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1761164303764/4ba27180-49f7-4485-a1a5-73f2f419ab9b.gif" alt="Final Optimized" class="image--center mx-auto" width="1138" height="640" loading="lazy"></p>
<p>Stopping it and running <code>index.js</code> again clearly shows the original implementation is slower.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1761164358090/4c3b9056-b936-4341-9302-461c290ea70e.gif" alt="Final unoptimized" class="image--center mx-auto" width="1138" height="640" loading="lazy"></p>
<h3 id="heading-performance-metrics">Performance Metrics</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>File</strong></td><td><strong>Route</strong></td><td><strong>Approx. Response Time</strong></td><td><strong>Notes</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>index.js</code></td><td><code>/blocking</code></td><td>Much longer</td><td>This is the original implementation. The single-threaded loop blocks the event loop, causing delays.</td></tr>
<tr>
<td><code>index-optimized.js</code></td><td><code>/blocking</code></td><td>Around 3 seconds</td><td>Here, the work is divided into multiple worker threads, making the process much faster.</td></tr>
</tbody>
</table>
</div><h3 id="heading-key-takeaways">Key Takeaways</h3>
<p>This comparison demonstrates how dividing the work into multiple parts using worker threads can make CPU-intensive tasks far more efficient, keeping the main thread responsive and improving overall performance.</p>
<h2 id="heading-summary">Summary</h2>
<p>So, first we saw in <code>index.js</code> how a blocking task can be handled in a <code>non-blocking</code>, asynchronous way. That is, we ran a worker thread, and because of this worker thread, the main thread didn't get blocked, allowing other users to continue their tasks simultaneously.</p>
<h3 id="heading-the-multi-core-challenge">The Multi-Core Challenge</h3>
<p>But the problem is, when we use a new thread on the server, there isn't just a single core. Usually, there are multiple cores, like <code>8</code>, <code>16</code>, or more. To use multiple cores, we first need to find out how many cores are available on the server.</p>
<h3 id="heading-discovering-available-cores">Discovering Available Cores</h3>
<p>If the server is Linux, we can easily find out the total number of cores using the <code>nproc</code> command. Then we can decide how many cores to use. For example, let's say we decide to use three cores. In <code>index-optimized.js</code>, we've implemented a way to divide the work among these cores.</p>
<h3 id="heading-asynchronous-worker-creation">Asynchronous Worker Creation</h3>
<p>So, what we did was wrap the worker creation process in a promise. Since creating a worker takes some time and spinning it up isn't instantaneous, this process is done asynchronously. This way, even if multiple users hit the endpoint to create Workers, the main thread won't be blocked.</p>
<h3 id="heading-how-to-implement-multi-core-optimization-1">How to Implement Multi-Core Optimization</h3>
<p>We simply created workers, and then using the <code>createWorker</code> function inside a loop, we spawned four or a specified number of Workers based on the thread count. Each worker posts messages independently, and through the listener, we receive data from each worker. These results are collected via promises, stored together in an array, and finally, we sum all the results from this array to get the final outcome.</p>
<p>So, the other concepts are all part of basic JavaScript. I hope you now understand how worker threads work and how we can use multi-threaded processes in Node.js. It's an excellent concept and a great opportunity to learn thoroughly.</p>
<h3 id="heading-what-we-learned"><strong>What We Learned</strong></h3>
<p>Worker Threads in Node.js provide a powerful way to handle CPU-intensive tasks without blocking the main event loop. By leveraging multiple cores and distributing work across threads, we can significantly improve application performance while maintaining responsiveness for other users.</p>
<ul>
<li><p><strong>Non-blocking execution</strong>: Worker threads prevent the main thread from being blocked</p>
</li>
<li><p><strong>Multi-core utilization</strong>: We can leverage multiple CPU cores for parallel processing</p>
</li>
<li><p><strong>Asynchronous worker creation</strong>: Using promises to handle worker creation without blocking</p>
</li>
<li><p><strong>Result aggregation</strong>: Collecting and combining results from multiple workers</p>
</li>
<li><p><strong>Performance optimization</strong>: Distributing heavy computations across multiple threads</p>
</li>
</ul>
<p>This approach is particularly valuable for applications that need to handle computationally intensive tasks while remaining responsive to user requests.</p>
<h2 id="heading-final-words">Final Words</h2>
<p>If you found the information here valuable, feel free to share it with others who might benefit from it. I’d really appreciate your thoughts – mention me on X <a target="_blank" href="https://x.com/sumit_analyzen">@sumit_analyzen</a> or on Facebook <a target="_blank" href="https://facebook.com/sumit.analyzen">@sumit.analyzen</a>, <a target="_blank" href="https://youtube.com/@logicBaseLabs">watch my coding tutorials</a>, <a target="_blank" href="https://sumitsaha.me">visit my website</a> or simply <a target="_blank" href="https://www.linkedin.com/in/sumitanalyzen/">connect with me</a> on LinkedIn.</p>
<h2 id="heading-additional-resources">Additional Resources</h2>
<p>You can also check the <a target="_blank" href="https://nodejs.org/api/worker_threads.html">Node.js Worker Threads documentation</a> for more in-depth learning. You can find all the source code from this tutorial in <a target="_blank" href="https://github.com/logicbaselabs/node-worker-threads/">this GitHub repository</a>. If it helped you in any way, consider giving it a star to show your support!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Multithreading for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ Multithreading is a crucial concept in computer science that allows for the concurrent execution of two or more threads, enabling more efficient and optimized use of resources. It can significantly improve the performance of applications, particularl... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/multithreading-for-beginners/</link>
                <guid isPermaLink="false">6696d8868866bc2fa7529e49</guid>
                
                    <category>
                        <![CDATA[ multithreading ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Tue, 16 Jul 2024 20:31:02 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1721161834666/59be7256-988c-491c-a745-985c5cbac06d.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Multithreading is a crucial concept in computer science that allows for the concurrent execution of two or more threads, enabling more efficient and optimized use of resources. It can significantly improve the performance of applications, particularly those that require heavy computational work or need to handle multiple tasks simultaneously. Understanding multithreading is essential for developing robust and efficient software, especially in languages like Java where this concept is extensively used.</p>
<p>We just published a course on the <a target="_blank" href="http://freeCodeCamp.org">freeCodeCamp.org</a> YouTube channel that will teach you all about multithreading in Java. This comprehensive course covers everything from the basics to advanced topics, providing both theoretical knowledge and practical code examples. While the primary focus is on Java, the principles and techniques discussed are applicable to other programming languages as well. Ramendu created this course.</p>
<h3 id="heading-why-learn-multithreading">Why Learn Multithreading?</h3>
<p>Multithreading is fundamental to creating high-performance applications. With the rise of multi-core processors, leveraging multiple threads has become essential to fully utilize the capabilities of modern hardware. Applications that perform CPU-intensive tasks, such as data processing, simulations, and complex calculations, can see large performance improvements when implemented with multithreading. Additionally, multithreading is important for creating responsive user interfaces in applications where long-running tasks are offloaded to separate threads, preventing the UI from freezing and ensuring a smooth user experience.</p>
<p>Learning multithreading not only enhances your programming skills but also opens up numerous career opportunities. Many high-demand fields, including game development, finance, and big data, require a solid understanding of concurrent programming.</p>
<h3 id="heading-course-content-overview">Course Content Overview</h3>
<p>The course begins with an introduction to the instructor and an overview of what you can expect to learn. You'll start with the basics, such as understanding what multithreading is and how it differs from sequential execution. From there, you'll learn how to create threads using both the <code>Runnable</code> interface and the <code>Thread</code> class, and explore the differences between these two approaches.</p>
<p>As you progress, the course teaches more complex topics such as the <code>join</code> method, daemon threads, and thread priority. You'll learn about synchronized blocks and the potential problems they can cause, as well as how to use the <code>wait</code> and <code>notify</code> methods for inter-thread communication. The producer-consumer problem is also covered, providing a practical example of these concepts in action.</p>
<p>The course also introduces the <code>ExecutorService</code> framework, which simplifies thread management by providing a pool of reusable threads. You'll explore different types of executors, including single-thread, fixed-thread, cached-thread, and scheduled-thread pools, and learn how to choose the ideal pool size for your needs. Advanced concepts such as <code>Callable</code> and <code>Future</code>, synchronized collections, and various concurrency utilities like <code>CountdownLatch</code>, <code>BlockingQueue</code>, <code>ConcurrentMap</code>, <code>CyclicBarrier</code>, and <code>Exchanger</code> are also covered.</p>
<p>Towards the end of the course, you'll learn about the importance of locks and how to use different types of locks such as reentrant locks and read-write locks. The visibility problem in Java, deadlocks, atomic variables, semaphores, and mutexes are discussed to provide a thorough understanding of these critical issues. Finally, the course covers the <code>ForkJoinPool</code>, an advanced framework for parallel execution, before concluding with a summary and a thank-you message.</p>
<p>This course is perfect for anyone looking to master multithreading in Java, from beginners to experienced developers seeking to deepen their understanding. Watch the full course on <a target="_blank" href="https://www.youtube.com/watch?v=gvQGKRlgop4">the freeCodeCamp.org YouTube channel</a> (6-hour watch).</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/gvQGKRlgop4" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Solve the Producer-Consumer Problem in Java using Multithreading ]]>
                </title>
                <description>
                    <![CDATA[ Concurrency is an important part of Java applications. Each application has multiple processes running at the same time. This helps utilize resources efficiently and improve performance. Multithreading is a method of achieving concurrency. It uses th... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/java-multithreading-producer-consumer-problem/</link>
                <guid isPermaLink="false">66d85157f01807d1f69107db</guid>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ multithreading ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kunal Nalawade ]]>
                </dc:creator>
                <pubDate>Mon, 04 Mar 2024 17:48:32 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/03/producer-consumer-problem-image.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Concurrency is an important part of Java applications. Each application has multiple processes running at the same time. This helps utilize resources efficiently and improve performance.</p>
<p>Multithreading is a method of achieving concurrency. It uses the concept of threads – lightweight processes – to execute multiple tasks in parallel. A very popular application of multithreading is the producer-consumer problem.</p>
<p>In this tutorial, we are going to understand what the producer-consumer problem is and touch upon threads and multithreading briefly. Then, we are going to understand how to solve the producer-consumer problem in Java using threads.</p>
<p>Now, I assume you have a basic knowledge of Java. If not, then check out the following resources.</p>
<ul>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/learn-java-free-java-courses-for-beginners/">Free Java Courses for Beginners</a></p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/learn-the-basics-of-java-programming/">Basics of Java Programming</a></p>
</li>
</ul>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-the-producer-consumer-problem">What is the Producer-Consumer Problem?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-solution-using-producer-and-consumer-threads">Solution using Producer and Consumer Threads and Issue with Synchronization</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-introducing-synchronization-in-the-message-queue">Introducing Synchronization in the Message Queue Class</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-producer-with-multiple-consumers">Producer with Multiple Consumers</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-solution-using-java-concurrencys-blockingqueue-class">Solution using Java Concurrency's BlockingQueue Class</a></p>
</li>
</ul>
<h2 id="heading-what-is-the-producer-consumer-problem">What is the Producer-Consumer Problem?</h2>
<p>The producer-consumer problem is a synchronization problem between different processes. There are three entities in this problem: a producer, a consumer, and a memory buffer. Both the producer and consumer share the same memory buffer.</p>
<p>The producer produces some items and pushes them into the memory buffer. A consumer then consumes these items by popping them out of the buffer. If the buffer is empty, then the consumer waits for the producer to push an item, which it consumes after the producer pushes it.</p>
<p>The memory buffer is of fixed size. If it is full, the producer waits for the consumer to consume an item before pushing a new one. The producer and consumer cannot access the buffer at the same time – that is, it's mutually exclusive. Each process should wait for the other to finish its work on the buffer before it can access the buffer.</p>
<p>Operating systems often encounter this problem where multiple processes access the same memory space to perform their tasks.</p>
<p>We will solve this problem using multithreading, so I assume you have a basic idea about what multithreading is and how it works. If not, then you can <a target="_blank" href="https://www.freecodecamp.org/news/how-to-get-started-with-multithreading-in-java/">read through this tutorial</a>.</p>
<p>We'll start with an attempt to solve it simply using threads and a separate class for message queue. Then, we'll understand its issues and how to overcome them in the next approach. We'll also see other approaches to the problem. Make sure to stick around until the end.</p>
<h2 id="heading-solution-using-producer-and-consumer-threads">Solution using Producer and Consumer Threads</h2>
<p>Let's go over our requirements first.</p>
<ul>
<li><p>Producer and Consumer tasks run in separate threads</p>
</li>
<li><p>Common data bus, typically a message queue, used by both producer and consumer.</p>
</li>
<li><p>If not full, producer pushes data into queue, or waits for it to be consumed</p>
</li>
<li><p>If not empty, consumer takes data out of the queue, or waits for producer to publish.</p>
</li>
</ul>
<p>These are the things we need to implement to solve this problem. Let's create the message queue first.</p>
<h3 id="heading-message-queue">Message Queue</h3>
<p>To set up a message queue, we'll use a class that contains the queue and methods to publish and consume messages.</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Data</span> </span>{ 
    Queue&lt;String&gt; q; 
    <span class="hljs-keyword">int</span> capacity; 

    Data(<span class="hljs-keyword">int</span> cap) { 
        q = <span class="hljs-keyword">new</span> LinkedList&lt;&gt;(); 
        capacity=cap; 
    } 
    <span class="hljs-comment">// other methods </span>
}
</code></pre>
<p>Here, we have used Java's <code>Queue</code> class to store our messages. Each message is of type <code>String</code>. But in bigger applications, the message or payload could be of any object type. We also define the capacity of the message queue.</p>
<p>Next, we'll implement the <code>publish()</code> method. The method accepts a new message to be published.</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">publish</span><span class="hljs-params">(String msg)</span> </span>{ <span class="hljs-comment">// publish message to the queue }</span>
</code></pre>
<p>First, we check if the queue is full. We can't publish a new message if the queue has reached capacity.</p>
<pre><code class="lang-java"><span class="hljs-keyword">if</span>(q.size() == capacity){ 
    <span class="hljs-keyword">return</span>; 
}
</code></pre>
<p>If the queue is not full, then add the message to the queue.</p>
<pre><code class="lang-java">q.add(msg);
</code></pre>
<p>We'll add print statements to understand the workflow better.</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">publish</span><span class="hljs-params">(String msg)</span> </span>{ 
    String name=Thread.currentThread().getName(); 
    <span class="hljs-keyword">if</span>(q.size() == capacity){ 
        System.out.println(<span class="hljs-string">"Queue Full!"</span>+name+<span class="hljs-string">" waiting for message to be consumed..."</span>); 
        <span class="hljs-keyword">return</span>; 
    } 
    q.add(msg); 
    System.out.println(<span class="hljs-string">"Message published:: "</span>+msg); 
    System.out.println(<span class="hljs-string">"Queue: "</span>+ q); 
    System.out.println(); 
}
</code></pre>
<p>Here, we just print the thread that is inside the method, the message published, and the resulting queue.</p>
<p>Let's implement the <code>consume()</code> method now. This method does not take any arguments and works similarly to the <code>publish()</code> method. We first check if the queue is empty, before removing anything from the queue.</p>
<pre><code class="lang-java"><span class="hljs-keyword">if</span>(q.size()==<span class="hljs-number">0</span>){ 
    <span class="hljs-keyword">return</span>; 
}
</code></pre>
<p>Then, we remove the message.</p>
<pre><code class="lang-java">q.poll();
</code></pre>
<p>Again, we'll add print statements to understand the workflow better.</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">consume</span><span class="hljs-params">()</span>  </span>{ 
    String name=Thread.currentThread().getName(); 
    <span class="hljs-keyword">if</span>(q.size()==<span class="hljs-number">0</span>){ 
        System.out.println(name+<span class="hljs-string">" waiting for new message..."</span>); 
        <span class="hljs-keyword">return</span>; 
    } 
    String msg = q.poll(); 
    System.out.println(name+<span class="hljs-string">" has consumed msg:: "</span>+msg); 
    System.out.println(<span class="hljs-string">"Queue: "</span>+ q); 
    System.out.println(); 
}
</code></pre>
<h3 id="heading-producer-thread">Producer Thread</h3>
<p>Let's write the producer logic now. We'll create a class <code>Producer</code> that will run in a thread. There are <a target="_blank" href="https://www.javatpoint.com/how-to-create-a-thread-in-java">several ways to create threads</a> in Java. We'll use the <code>Runnable</code> interface to create our thread since it's the most preferred approach.</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Producer</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Runnable</span></span>{ 
    Data data; 
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Producer</span><span class="hljs-params">(Data data)</span> </span>{ 
        <span class="hljs-keyword">this</span>.data = data; 
    } 

    <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>{ } 
}
</code></pre>
<p>The producer has access to the data bus object which is passed to it via the constructor. The producer logic goes inside the <code>run()</code> method. By overriding the run method, you are writing functionality that runs in a thread.</p>
<p>Now, a producer's ways of producing and publishing data differs in every application. For this post, we are going to simulate a functionality where the producer keeps publishing messages every few seconds.</p>
<p>We'll define a list of messages that the producer can use.</p>
<pre><code class="lang-java"><span class="hljs-keyword">final</span> String[] messages={<span class="hljs-string">"Hi!!"</span>, <span class="hljs-string">"How are you!!"</span>, <span class="hljs-string">"I love you!"</span>, <span class="hljs-string">"What's going on?!!"</span>, <span class="hljs-string">"That's really funny!!"</span>};
</code></pre>
<p>Here's the producer logic inside the <code>run()</code> method:</p>
<pre><code class="lang-java"><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">int</span> i=<span class="hljs-number">0</span>; 
    <span class="hljs-keyword">try</span> { 
        <span class="hljs-keyword">while</span>(<span class="hljs-keyword">true</span>){ 
            Thread.sleep(<span class="hljs-number">1000</span>); 
            data.publish(messages[i]); 
            i=(i+<span class="hljs-number">1</span>)%messages.length; 
        } 
    } <span class="hljs-keyword">catch</span> (InterruptedException e) {} 
}
</code></pre>
<p>In this code, the producer is publishing a message from the messages list every 1000 ms. <code>Thread.sleep(_some_delay_)</code> pauses execution of the thread for a certain period. Since it throws an exception, we surround the code with a try-catch block.</p>
<p>This is just for demonstration purposes – don't worry about the logic. Our implementation works regardless of the producer or consumer logic.</p>
<h3 id="heading-consumer-thread">Consumer Thread</h3>
<p>Similar to producer thread, let's simulate the consumer logic.</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Consumer</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Runnable</span></span>{ 
    Data data; 
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Consumer</span><span class="hljs-params">(Data data)</span> </span>{ 
        <span class="hljs-keyword">this</span>.data = data; 
    } 
    <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">try</span> { 
            <span class="hljs-keyword">while</span>(<span class="hljs-keyword">true</span>){ 
                Thread.sleep(<span class="hljs-number">2000</span>); 
                data.consume(); 
            } 
        } <span class="hljs-keyword">catch</span> (InterruptedException e) {} 
    } 
}
</code></pre>
<p>Here, the consumer tries to consume a message every 2000 ms.</p>
<h3 id="heading-putting-it-all-together">Putting it all Together</h3>
<p>Now, we have our message queue along with the producer and consumer classes. Let's create one producer and one consumer thread and start them.</p>
<p>We'll create a <code>Data</code> object with capacity of 5 messages and create our producer and consumer threads with the objects of the <code>Producer</code> and <code>Consumer</code> classes.</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">Main</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>{ 
        Data data = <span class="hljs-keyword">new</span> Data(<span class="hljs-number">5</span>); 
        Thread producer=<span class="hljs-keyword">new</span> Thread(<span class="hljs-keyword">new</span> Producer(data), <span class="hljs-string">"producer"</span>); 
        Thread consumer=<span class="hljs-keyword">new</span> Thread(<span class="hljs-keyword">new</span> Consumer(data), <span class="hljs-string">"consumer"</span>);
        producer.start(); 
        consumer.start(); 
    } 
}
</code></pre>
<p>The <code>run()</code> method executes in a separate thread when <code>start()</code> is called.</p>
<h3 id="heading-output">Output:</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-23-211626-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Inconsistent output</em></p>
<p>Here, the output is inconsistent with the desired workflow. Even after publishing the first message, the consumer is still waiting. Then, a consumer has consumed a message <code>Hi!!</code> that doesn't exist. The state of the queue is also inconsistent.</p>
<p>You will probably get a different output, since thread execution depends on the core OS. But the issue still persists. Why does this happen?</p>
<h3 id="heading-synchronization-issue-with-the-data-class">Synchronization Issue With the Data Class</h3>
<p>Both producer and consumer threads run simultaneously, working on the same resource. They are accessing the message queue at the exact same time. Both the threads may start with one version of the resource and by the time they perform an operation, they are working on a different version.</p>
<p>This leads to a <a target="_blank" href="https://www.javatpoint.com/race-condition-in-operating-system">race</a> condition. Both threads end up competing for the same resource and give inconsistent results. The producer thread is trying to add a message to the queue, while at the same time a consumer is trying to consume a message. There's no way of controlling which message the consumer could get.</p>
<p>To solve this issue, we need some kind of mechanism to ensure that only one thread can operate on a shared resource at a time. In this case, we'll use the concept of <a target="_blank" href="https://www.geeksforgeeks.org/synchronization-in-java/">synchronization</a>.</p>
<p>At a glance, a synchronized function or a block can only be executed by one thread at a time. A thread entering such a block acquires a "lock" on the object and any other threads have to wait until the thread releases this lock – that is, until it finishes working on the shared resource.</p>
<p>We'll use a similar method to solve our issue.</p>
<h2 id="heading-introducing-synchronization-in-the-message-queue">Introducing Synchronization in the Message Queue</h2>
<p>To ensure the message queue is only accessed by one thread (producer or consumer) at a time, a thread needs to secure a lock on the <code>Data</code> object before performing any operations.</p>
<h3 id="heading-how-to-use-the-synchronized-keyword">How to Use the <code>synchronized</code> Keyword</h3>
<p>An object can be made mutually exclusive by using the synchronized keyword. We'll use the <code>synchronized</code> keyword with the <code>publish()</code> and <code>consume()</code> methods.</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">synchronized</span> <span class="hljs-keyword">void</span> <span class="hljs-title">publish</span><span class="hljs-params">(String msg)</span></span>
</code></pre>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">synchronized</span> <span class="hljs-keyword">void</span> <span class="hljs-title">consume</span><span class="hljs-params">()</span></span>
</code></pre>
<p>Now, a thread needs to acquire a lock on the object before entering these methods.</p>
<h3 id="heading-what-are-the-wait-and-notify-methods">What are the <code>wait()</code> and <code>notify()</code> Methods?</h3>
<p>We have achieved synchronization – only one thread can access a shared resource at a time to ensure consistency. Now, we need to establish communication between the producer and consumer threads.</p>
<p>Let's understand what we need first. If the queue is full, the producer needs to wait for a consumer to consume an item. Similarly, if the queue is empty, the consumer needs to wait until the producer pushes an item.</p>
<p>Also, when a producer pushes an item, it needs to notify all the waiting consumer threads about the action. The is also true when the consumer consumes an item. So, how do we establish this communication?</p>
<p>We can do this using the <code>wait()</code> and <code>notify()</code> methods. When the <code>wait()</code> method is called, the thread releases the lock on the object and enters a waiting state until another thread calls the <code>notify()</code> or <code>notifyAll()</code> method.</p>
<p><code>notify()</code> wakes up one thread that is in the waiting state, while <code>notifyAll()</code> wakes up all waiting threads. When a thread wakes up again, it has to re-acquire the lock on the object. If another thread has the lock, then this thread needs to wait until the other thread releases the lock.</p>
<p>You can learn more about the <code>wait()</code> and <code>notify()</code> methods <a target="_blank" href="https://www.baeldung.com/java-wait-notify">here</a>.</p>
<h3 id="heading-how-to-communicate-between-threads-using-wait-and-notify">How to Communicate Between Threads using wait() and notify()</h3>
<p>Let's use the above methods. A producer needs to wait before it pushes an item if the queue is full. So, invoke the <code>wait()</code> method if the queue is at capacity. Similarly, the consumer needs to wait if the queue is empty.</p>
<p>To wake up threads from the waiting state, call <code>notifyAll()</code> after the producer publishes a message and the consumer consumer a message. This will notify all the waiting threads.</p>
<p>Here is the updated <code>publish()</code> method:</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">synchronized</span> <span class="hljs-keyword">void</span> <span class="hljs-title">publish</span><span class="hljs-params">(String msg)</span> <span class="hljs-keyword">throws</span> InterruptedException </span>{ 
    String name=Thread.currentThread().getName(); 
    <span class="hljs-keyword">if</span>(q.size() == capacity){ 
        System.out.println(<span class="hljs-string">"Queue Full!"</span>+name+<span class="hljs-string">" waiting for message to be consumed..."</span>); 
        wait(); 
    } 
    q.add(msg); 
    System.out.println(<span class="hljs-string">"Message published:: "</span>+msg); 
    System.out.println(<span class="hljs-string">"Queue: "</span>+ q); 
    System.out.println(); 
    notifyAll(); 
}
</code></pre>
<p>And here's the updated <code>consume()</code> method:</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">synchronized</span> <span class="hljs-keyword">void</span> <span class="hljs-title">consume</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> InterruptedException </span>{ 
    String name=Thread.currentThread().getName(); 
    <span class="hljs-keyword">if</span>(q.size()==<span class="hljs-number">0</span>){ 
        System.out.println(name+<span class="hljs-string">" waiting for new message..."</span>); 
        wait(); 
     } 
    String msg = q.poll(); 
    System.out.println(name+<span class="hljs-string">" has consumed msg:: "</span>+msg);
    System.out.println(<span class="hljs-string">"Queue: "</span>+ q); 
    System.out.println(); 
    notifyAll(); 
}
</code></pre>
<p><code>wait()</code> and <code>notify()</code> can throw <code>InterruptedException</code>, so we add a <code>throws</code> declaration to the methods.</p>
<h3 id="heading-output-1">Output:</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-26-132435-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Output with Synchronization‌</em></p>
<p>This time, the output is more consistent and we are getting the expected behavior. The producer keeps publishing messages and the consumer consumes those messages.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-26-134924-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Producer waiting</em></p>
<p>Here, the queue is full and the producer waits for the consumer to consume a message. Only after that does the producer publish a new message.</p>
<h2 id="heading-producer-with-multiple-consumers">Producer with Multiple Consumers</h2>
<p>So far, we have tackled the problem with one producer and one consumer. In a real-world application, there could be multiple producers and consumers, all of them running in separate threads.</p>
<p>Let's add more consumer threads to see how we could handle this scenario:</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span>(int i=<span class="hljs-number">1</span>;i&lt;=<span class="hljs-number">5</span>;i++){ 
    new Thread(new Consumer(data), <span class="hljs-string">"Consumer "</span>+i).start();
}
</code></pre>
<p>Here, we have created 5 consumer threads, labelled them, and started them one by one. But, this is not enough. There is an issue with the existing approach.</p>
<p>Let's reduce the consumer sleep time and run the code:</p>
<pre><code class="lang-java">Thread.sleep(<span class="hljs-number">500</span>);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-26-203117.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Multiple consumers issue</em></p>
<p>Here, after consumer 5 has consumed a message, the other consumers are able to consume even if the queue is empty.</p>
<p>The issue lies in the following condition:</p>
<pre><code class="lang-java"><span class="hljs-keyword">if</span>(q.size()==<span class="hljs-number">0</span>){
    wait();
}
</code></pre>
<p>Let's understand the workflow first. Consider Consumer 5 (C5) and Consumer 1 (C1). C5 secures the lock on the method and enters it. The queue is initially empty, so it releases the lock and waits for the producer. At the same time, C1 secures the lock and enters the method. It also waits for the producer.</p>
<p>So, C5 and C1 are waiting. The producer publishes a message. C5 and C1 are notified and they wake up. C5 reacquires the lock and proceeds to consume the message, while C1 waits for C5 to release the lock. Here, C1 is not waiting because of <code>wait()</code> – it has woken up and now it's waiting at the next line.</p>
<p>After C5 consumes the message and releases the lock, C1 continues and tries to consume the message. But the queue is empty now, so it receives null or throws an exception. This also happens with the other threads.</p>
<p>To prevent this, we need to check if the queue is empty once again. So, instead of using an <code>if</code> condition, we use a <code>while</code> loop like this:</p>
<pre><code class="lang-python"><span class="hljs-keyword">while</span>(q.size()==<span class="hljs-number">0</span>){
            wait();
        }
</code></pre>
<p>This checks if the queue is empty every time a thread wakes up. So, if multiple threads wake up at the same time, it should check if another thread has emptied the queue.</p>
<p>We do the same for checking if the queue is full.</p>
<pre><code class="lang-java"><span class="hljs-keyword">while</span>(q.size() == capacity){
            wait();
        }
</code></pre>
<p>This time, the code runs without any issues.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-26-204943.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Multiple consumers correct output</em></p>
<p>Here is the complete code for <code>Data</code> class:</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Data</span> </span>{
    Queue&lt;String&gt; q;
    <span class="hljs-keyword">int</span> capacity;
    Data(<span class="hljs-keyword">int</span> cap) {
        q = <span class="hljs-keyword">new</span> LinkedList&lt;&gt;();
        capacity=cap;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">synchronized</span> <span class="hljs-keyword">void</span> <span class="hljs-title">publish</span><span class="hljs-params">(String msg)</span> <span class="hljs-keyword">throws</span> InterruptedException </span>{
        String name=Thread.currentThread().getName();
        <span class="hljs-keyword">while</span>(q.size() == capacity){
            System.out.println(<span class="hljs-string">"Queue Full!"</span>+name+<span class="hljs-string">" waiting for message to be consumed..."</span>);
            wait();
        }
        q.add(msg);
        System.out.println(<span class="hljs-string">"Message published:: "</span>+msg);
        System.out.println(<span class="hljs-string">"Queue: "</span>+ q);
        System.out.println();
        notifyAll(); 
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">synchronized</span> <span class="hljs-keyword">void</span> <span class="hljs-title">consume</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> InterruptedException </span>{
        String name=Thread.currentThread().getName();
        <span class="hljs-keyword">while</span>(q.size()==<span class="hljs-number">0</span>){
            System.out.println(name+<span class="hljs-string">" waiting for new message..."</span>);
            wait();
        }
        String msg = q.poll();
        System.out.println(name+<span class="hljs-string">" has consumed msg:: "</span>+msg);
        System.out.println(<span class="hljs-string">"Queue: "</span>+ q);
        System.out.println();
        notifyAll();
    }
}
</code></pre>
<p>You can create any number of producers and consumers and test this code in multiple scenarios.</p>
<h2 id="heading-solution-using-java-concurrencys-blockingqueue-class">Solution using Java Concurrency's BlockingQueue Class</h2>
<p>So far you have learned what the producer-consumer problem is and how it can be solved. But, while working on real-time applications, we probably won't implement synchronization manually.</p>
<p>Instead, we can use the <code>BlockingQueue</code> class from <code>java.util.concurrent</code> package. The difference between <code>Queue</code> and <code>BlockingQueue</code> is that it waits for the queue to become non-empty before a message can be consumed. Similarly, it waits for the queue to have space before publishing a new message.</p>
<p>We can initialize the blocking queue in the following way:</p>
<pre><code class="lang-java">BlockingQueue&lt;String&gt; q = <span class="hljs-keyword">new</span> ArrayBlockingQueue&lt;&gt;(<span class="hljs-number">10</span>);
</code></pre>
<p>This creates a blocking queue of capacity 10. To publish an item, we use the <code>put()</code> method, and to remove an item, we use the <code>take()</code> method.</p>
<p>Let's first use this in our Producer class:</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Producer</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Runnable</span></span>{
    BlockingQueue&lt;String&gt; q;
    <span class="hljs-keyword">final</span> String[] messages={<span class="hljs-string">"Hi!!"</span>, <span class="hljs-string">"How are you!!"</span>, <span class="hljs-string">"I love you!"</span>, <span class="hljs-string">"What's going on?!!"</span>, <span class="hljs-string">"That's really funny!!"</span>};
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Producer</span><span class="hljs-params">(BlockingQueue&lt;String&gt; q)</span> </span>{
        <span class="hljs-keyword">this</span>.q = q;
    }

    <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">int</span> i=<span class="hljs-number">0</span>;
        <span class="hljs-keyword">try</span> {
            <span class="hljs-keyword">while</span>(<span class="hljs-keyword">true</span>){
                Thread.sleep(<span class="hljs-number">500</span>);

                q.put(messages[i]);

                System.out.println(<span class="hljs-string">"Message published:: "</span>+messages[i]);
                i=(i+<span class="hljs-number">1</span>)%messages.length;
            }
        } <span class="hljs-keyword">catch</span> (InterruptedException e) {}
    }

}
</code></pre>
<p>Here, we are not using a separate <code>Data</code> class with synchronized methods, since the <code>put()</code> and <code>take()</code> methods of <code>BlockingQueue</code> are synchronized. Here, if the queue is full, the <code>put()</code> method waits for a consumer to consume a message.</p>
<p>Similarly, let's update our Consumer class:</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Consumer</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Runnable</span></span>{
    BlockingQueue&lt;String&gt; q;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Consumer</span><span class="hljs-params">(BlockingQueue&lt;String&gt; q)</span> </span>{
        <span class="hljs-keyword">this</span>.q = q;
    }

    <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">try</span> {
            <span class="hljs-keyword">while</span>(<span class="hljs-keyword">true</span>){
                Thread.sleep(<span class="hljs-number">1500</span>);

                String msg=q.take();

                String name=Thread.currentThread().getName();
                System.out.println(name+<span class="hljs-string">" has consumed msg:: "</span>+msg);
            }
        } <span class="hljs-keyword">catch</span> (InterruptedException e) {}
    }    
}
</code></pre>
<p>Here, if the queue is empty, the <code>take()</code> method waits for the producer to publish a message.</p>
<p>Let's create our <code>BlockingQueue</code> object and start these threads:</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">Main</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>{
        BlockingQueue&lt;String&gt; q = <span class="hljs-keyword">new</span> ArrayBlockingQueue&lt;&gt;(<span class="hljs-number">10</span>);
        Thread producer = <span class="hljs-keyword">new</span> Thread(<span class="hljs-keyword">new</span> Producer(q));
        producer.start();
        <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i=<span class="hljs-number">1</span>;i&lt;=<span class="hljs-number">5</span>;i++){
            <span class="hljs-keyword">new</span> Thread(<span class="hljs-keyword">new</span> Consumer(q), <span class="hljs-string">"Consumer "</span>+i).start();
        }
    }

}
</code></pre>
<p>Here, we have one producer thread and 5 consumer threads. Let's see the output:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-28-115531.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Output for BlockingQueue implementation</em></p>
<p>In the output, you can see that after consumers 1, 3, and 2 have consumed a message, the other consumers wait for a message to be published before consuming it.</p>
<p>There could be a few inconsistencies while printing these messages since the thread only stops at the <code>put()</code> or <code>take()</code> methods and not the <code>println()</code> statements. But the code runs properly. Again, the output will be different each time you run the code.</p>
<p>So, while working on big projects, you can use the <code>BlockingQueue</code> class. But it's important to understand how to deal with the whole producer-consumer problem from scratch. This is really helpful, especially during interviews, since you typically won't be allowed to use the <code>BlockingQueue</code> class.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, you learned about an important problem in concurrency, the product-consumer problem. And you learned how you can solve it using multithreading in Java.</p>
<p>In total, we implemented four different approaches:</p>
<p>First, I started out with a very basic and straightforward implementation. Running the producer and consumer in separate threads helped achieve concurrency. But since they used the same message queue, there was a synchronization problem.</p>
<p>Therefore, in the next approach, we added synchronization to fix the issue. Then, we added more consumers who would all wait for the producer. There, we learned why it is important to check the full and empty conditions every time a thread wakes up.</p>
<p>After going through the whole implementation from scratch, we saw a simple way to solve the Producer-Consumer problem in Java using BlockingQueue. By understanding different approaches and their issues, you can get a better idea of how to tackle a problem. I hope this guide helps with your future endeavors.</p>
<p>If you are unable to understand the content or find the explanation unsatisfactory, let me know. New ideas are always appreciated! Feel free to connect with me on Twitter. Till then, goodbye!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What are Threads in Java? How to Create a Thread with Examples ]]>
                </title>
                <description>
                    <![CDATA[ By Bikash Daga (Jain) Threads in Java are pre-defined classes that are available in the java.package when you write your programs. Generally, every program has one thread which is provided from the java.package.  All of these threads use the same mem... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-are-threads-in-java-how-to-create-one/</link>
                <guid isPermaLink="false">66d45dd9182810487e0ce103</guid>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ multithreading ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 28 Nov 2022 22:23:36 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/11/Copy-of-Copy-of-How-Encapsulation-is-Achieved-in-Python--1-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Bikash Daga (Jain)</p>
<p>Threads in Java are pre-defined classes that are available in the java.package when you write your programs. Generally, every program has one thread which is provided from the java.package. </p>
<p>All of these threads use the same memory, but they are independent. This means that any exception in a thread will not affect how other threads work, despite them sharing the same memory.</p>
<h2 id="heading-what-youll-learn">What You'll Learn:</h2>
<ul>
<li>In this article we will learn about how to create a thread</li>
<li>We will learn about the concept of multi tasking.</li>
<li>We will learn about the lifecycle of threads and also about the thread class.</li>
</ul>
<h2 id="heading-what-are-threads-in-java">What are Threads in Java?</h2>
<p>Threads allow us to do things more quickly in Java. That is, they help us perform multiple things all at once. </p>
<p>You use threads to perform complex operations without any disturbance in the main program. </p>
<p>When various multiple threads are executed at the same time, this process is known as multi-threading. </p>
<p><a target="_blank" href="https://www.freecodecamp.org/news/how-to-get-started-with-multithreading-in-java/">Multi-threading</a> is mainly used in gaming and similar programs. Since we now know a bit about multi-threading, let's also learn about the concept of multi-tasking.</p>
<h2 id="heading-what-is-multitasking-in-java">What is Multitasking in Java?</h2>
<p><a target="_blank" href="https://www.techtarget.com/whatis/definition/multitasking">Multitasking</a> is the process that lets users perform multiples tasks at the same time. There are two ways to enable multitasking in Java:</p>
<ol>
<li><strong>Process-based multitasking</strong>: The processes in this type of multitasking are heavy and a lot of time is consumed. This is because the program takes a long time to switch between different processes.</li>
<li><strong>Thread-based multi tasking</strong>: Threads are light-weight compared to process-based multi tasking, and the time taken to switch between them is shorter.</li>
</ol>
<p>Now let's learn about the working model of a thread.</p>
<h2 id="heading-thread-lifecycle-in-java">Thread Lifecycle in Java</h2>
<h3 id="heading-what-is-a-thread-lifecycle-in-java">What is a thread lifecycle in Java?</h3>
<p>In Java, a thread will always remain in one of a few different states (which we will read about below). </p>
<p>The thread goes through various stages in its lifecycle. For example a thread is first born, then it gets started, and goes through these various stages until it dies. </p>
<p>The thread model consists of various states. Let's learn about each of them in more detail:</p>
<ol>
<li><strong>New</strong>: the model is in the new state when the code is not yet running.</li>
<li><strong>Running state or the active stage</strong>: this is the state when the program is under execution or is ready to execute.</li>
<li><strong>Suspended state</strong>: you can use this state if you want to pause activity when something specific happens (and lets you temporarily stop execution).</li>
<li><strong>Blocked state</strong>: a thread is under the blocked state when it's waiting for resources. In the blocked state, the thread scheduler clears the queue by rejecting unwanted threads which are present.</li>
<li><strong>Terminated state</strong>: this state stops a thread's execution immediately. A terminated thread means that it is dead and is no longer available for use.</li>
</ol>
<h2 id="heading-thread-methods">Thread Methods</h2>
<h3 id="heading-what-are-thread-methods-in-java">What are thread methods in Java?</h3>
<p>Thread methods in Java are very important while you're working with a multi-threaded application. The thread class has some important methods which are described by the thread itself.</p>
<p>Now let's learn about each of these methods:</p>
<ol>
<li><strong>public void start()</strong>: you use this method to start the thread in a separate path of execution. Then it invokes the run() method on the thread object.</li>
<li><strong>public void run()</strong>: this method is the starting point of the thread. The execution of the thread begins from this process.</li>
<li><strong>public final void setName()</strong>: this method changes the name of the thread object. There is also a <code>getName()</code> method for retrieving the name of the current context.</li>
<li><strong>public final void setPriority()</strong>: you use this method to set the values of the thread object.</li>
<li><strong>public void sleep()</strong>: you use this method to suspend the thread for a particular amount of time.</li>
<li><strong>public void interrupt()</strong>: you use this method to interrupt a particular thread. It also causes it to continue execution if it was blocked for any reason.</li>
<li><strong>public final boolean isAlive()</strong>: this method returns true if the thread is alive.</li>
</ol>
<p>Now let's learn about creating a thread.</p>
<h2 id="heading-how-to-create-a-thread-in-java">How to Create a Thread in Java</h2>
<p>There are two ways to create a thread:</p>
<p>First, you can create a thread using the thread class (extend syntax). This provides you with constructors and methods for creating and operating on threads.</p>
<p>The thread class extends the object class and implements a runnable interface. The thread class in Java is the main class on which Java’s multithreading system is based.</p>
<p>Second, you can create a thread using a runnable interface. You can use this method when you know that the class with the instance is intended to be executed by the thread itself. </p>
<p>The runnable interface is an interface in Java which is used to execute concurrent thread. The runnable interface has only one method which is <code>run()</code>.</p>
<p>Now let's see the syntax of both of them:</p>
<h4 id="heading-how-to-use-the-extend-syntax">How to use the extend syntax:</h4>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">thread</span> </span>{
  public <span class="hljs-keyword">void</span> test() {
    System.out.println(<span class="hljs-string">"Threads are very helpful in java"</span>);
  }
}
</code></pre><p>Here's an example of the <code>extend</code> method:</p>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">test</span> </span>{
  public <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> main(<span class="hljs-built_in">String</span>[] args) {
    Main test = <span class="hljs-keyword">new</span> Main();
    test.start();
    System.out.println(<span class="hljs-string">"Threads are very much helpful in java"</span>);
  }
  public <span class="hljs-keyword">void</span> run() {
    System.out.println(<span class="hljs-string">"Threads are very helpful in java"</span>);
  }
}
</code></pre><p>Using the syntax of the extended class we have just implemented it in this example. Run the above code in your editor to see how it works.</p>
<h4 id="heading-how-to-use-a-runnable-interface">How to use a runnable interface:</h4>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> <span class="hljs-title">implements</span> <span class="hljs-title">runnable</span> </span>{
  public <span class="hljs-keyword">void</span> test() {
    System.out.println(<span class="hljs-string">"Threads are very helpful in java"</span>);
  }
}
</code></pre><p>And here's an example of using a <a target="_blank" href="https://docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html">runnable interface</a>:</p>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">cal</span> <span class="hljs-title">implements</span> <span class="hljs-title">test</span> </span>{
  public <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> main(<span class="hljs-built_in">String</span>[] args) {
    cal obj = <span class="hljs-keyword">new</span> cal();
    Thread thread = <span class="hljs-keyword">new</span> Thread(obj);
    thread.start();
    System.out.println(<span class="hljs-string">"Threads are very much helpful in java"</span>);
  }
  public <span class="hljs-keyword">void</span> run() {
    System.out.println(<span class="hljs-string">"Threads are very much helpful in java"</span>);
  }
}
</code></pre><p>Since we extended the thread class, our class object will not be treated as a thread object. Run the above code in your compiler to see how it works.</p>
<h2 id="heading-how-to-implement-threads-in-java-examples">How to Implement Threads in Java – Examples</h2>
<p>Let's see few more examples of implementing <a target="_blank" href="https://www.scaler.com/topics/thread-in-java/">threads in Java</a>:</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">First</span>
</span>{
public <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> main (<span class="hljs-built_in">String</span> [ ]args) throws IOException
{
Thread t =Thread.currentThread( );
System.out.println(“CURRENTTHREAD = ” + t);
t.setName(“NewThread”);
t.setPriority(t.getPriority( ) – <span class="hljs-number">1</span>);
System.out.println(“CURRENTTHREAD = ” + t);
System.out.println(“NAME = ” + t.getName( ));
}
}
</code></pre><h4 id="heading-output">Output</h4>
<pre><code>CURRENTTHREAD =THREAD [main, <span class="hljs-number">5</span>, main]
CURRENTTHREAD =THREAD [New Thread, <span class="hljs-number">4</span>, main]
NAME = New Thread
</code></pre><p>Here we have created a thread then printed the current thread. Then we have set the name of the thread as a new thread and finally we have printed the name of the thread. Run the above code in your editor to see how it works.</p>
<p>Here's another example:</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">First</span> <span class="hljs-title">implements</span> <span class="hljs-title">Runnable</span>
</span>{
Thread t;
First( ){
t = <span class="hljs-keyword">new</span> Thread(<span class="hljs-built_in">this</span>,<span class="hljs-string">"NEW"</span>);
System.out.println(“CHILD :” + t);
t.start();
}
public <span class="hljs-keyword">void</span> run( ) {
<span class="hljs-keyword">try</span>{ <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">5</span>; i&gt;<span class="hljs-number">0</span>, i- -) {
System.out.println(<span class="hljs-string">"CHILD :"</span> + i);
Thread.sleep(<span class="hljs-number">500</span>); }
} <span class="hljs-comment">//END OFTRY BLOCK</span>
<span class="hljs-keyword">catch</span>(InterruptedException e){ }
System.out.println(<span class="hljs-string">"EXITING CHILD"</span>);
} }
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Second</span>
</span>{
public <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> main(<span class="hljs-built_in">String</span> [ ]args) throws IOException
{
<span class="hljs-keyword">new</span> First();
<span class="hljs-keyword">try</span>{
<span class="hljs-keyword">for</span>(int i = <span class="hljs-number">5</span>; i&gt;<span class="hljs-number">0</span>, i- -)
{
System.out.println(<span class="hljs-string">"MAIN :"</span>  + i);
Thread.sleep(<span class="hljs-number">1000</span>);
}
} <span class="hljs-comment">//END OFTRY BLOCK</span>
<span class="hljs-keyword">catch</span>(InterruptedException e){ }
System.out.println(<span class="hljs-string">"Exiting man"</span>);
}
}
</code></pre><h4 id="heading-output-1">Output</h4>
<pre><code>CHILD = THREAD [NEW, <span class="hljs-number">5</span>, main]
<span class="hljs-attr">MAIN</span> : <span class="hljs-number">5</span>
<span class="hljs-attr">CHILD</span> : <span class="hljs-number">5</span>
<span class="hljs-attr">CHILD</span> : <span class="hljs-number">4</span>
<span class="hljs-attr">MAIN</span> : <span class="hljs-number">4</span>
<span class="hljs-attr">CHILD</span> : <span class="hljs-number">3</span>
<span class="hljs-attr">CHILD</span> : <span class="hljs-number">2</span>
<span class="hljs-attr">MAIN</span> : <span class="hljs-number">3</span>
<span class="hljs-attr">CHILD</span> : <span class="hljs-number">1</span>
EXITING CHILD
<span class="hljs-attr">MAIN</span> : <span class="hljs-number">2</span>
<span class="hljs-attr">MAIN</span> : <span class="hljs-number">1</span>
EXITING MAIN
</code></pre><p>Here we have created a thread and then printed the child thread. Then we ran the for loop inside the run function and printed the child. Run the code in your editor to see how it works.</p>
<p>Now let's learn more about multi threading.</p>
<h2 id="heading-multi-threading-in-java">Multi-Threading in Java</h2>
<p>As I briefly explained above, multithreading in Java refers to the execution of several threads at the same time. </p>
<p>Multithreading is useful because threads are independent – and in multithreading we can perform the execution of several threads at the same time without blocking the user. </p>
<p>It also helps us save time as we can perform several operation at the same time. A good real time example of multi threading in Java is word processing. This program checks the spelling of what we're typing while we write a document. In this case each task will be provided by a different thread.</p>
<h3 id="heading-use-cases-of-multi-threading-in-java">Use cases of multi-threading in Java</h3>
<p>Now that you know how multi-threading saves time by allowing you to perform multiple operation together, let's learn about some practical uses cases of multi-threading:</p>
<ol>
<li>Word processing, which we discussed above.</li>
<li>Gaming.</li>
<li>Improving the responsiveness of a server.</li>
<li>Using thread synchronization functions to provide enhanced processes to process communication.</li>
</ol>
<p>Now let's look at an example program to learn how to implement multithreading:</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">First</span> <span class="hljs-title">implements</span> <span class="hljs-title">Runnable</span>
</span>{
Thread t; <span class="hljs-built_in">String</span> S;
First(<span class="hljs-built_in">String</span> Name){
S=Name;
t = <span class="hljs-keyword">new</span> Thread(<span class="hljs-built_in">this</span>,S);
System.out.println(<span class="hljs-string">"CHILD :"</span> + t);
t.start();
}
public <span class="hljs-keyword">void</span> run( ) {
<span class="hljs-keyword">try</span>{ <span class="hljs-keyword">for</span>(int i = <span class="hljs-number">5</span>; i&gt;<span class="hljs-number">0</span>, i- -) {
System.out.println(S + <span class="hljs-string">" :"</span> + i);
Thread.sleep(<span class="hljs-number">1000</span>); }
} <span class="hljs-comment">//END OF TRY BLOCK</span>
<span class="hljs-keyword">catch</span>(InterruptedException e){ }
System.out.println(<span class="hljs-string">"EXITING "</span> + S);
} 
}
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Second</span>
</span>{
public <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> main(<span class="hljs-built_in">String</span> [ ]args) throws IOException
{
<span class="hljs-keyword">new</span> First(<span class="hljs-string">"ONE"</span>);
<span class="hljs-keyword">new</span> First(<span class="hljs-string">"TWO"</span>);
<span class="hljs-keyword">new</span> First(<span class="hljs-string">"THREE"</span>);
<span class="hljs-keyword">try</span>{
Thread.sleep(<span class="hljs-number">20000</span>);
} <span class="hljs-comment">//END OFTRY BLOCK</span>
<span class="hljs-keyword">catch</span>(InterruptedException e){ }
System.out.println(<span class="hljs-string">"EXITING MAIN"</span>);
</code></pre><h4 id="heading-output-2">Output</h4>
<pre><code>CHILD =THREAD [ONE, <span class="hljs-number">5</span>, main]
CHILD =THREAD [TWO, <span class="hljs-number">5</span>, main]
CHILD =THREAD [THREE, <span class="hljs-number">5</span>, main]
<span class="hljs-attr">ONE</span> : <span class="hljs-number">5</span> ONE : <span class="hljs-number">2</span>
<span class="hljs-attr">TWO</span> : <span class="hljs-number">5</span> TWO : <span class="hljs-number">2</span>
<span class="hljs-attr">THREE</span> : <span class="hljs-number">5</span> THREE:<span class="hljs-number">2</span>
<span class="hljs-attr">ONE</span> : <span class="hljs-number">4</span> ONE : <span class="hljs-number">1</span>
<span class="hljs-attr">TWO</span> : <span class="hljs-number">4</span> TWO : <span class="hljs-number">1</span>
<span class="hljs-attr">THREE</span> : <span class="hljs-number">4</span> THREE : <span class="hljs-number">1</span>
<span class="hljs-attr">ONE</span> : <span class="hljs-number">3</span> EXITING ONE
<span class="hljs-attr">TWO</span> : <span class="hljs-number">3</span> EXITINGTWO
<span class="hljs-attr">THREE</span> : <span class="hljs-number">3</span> EXITINGTHREE
EXITING MAIN
</code></pre><p>In the code above, we have implemented multi-threading by using the run method. Then we have initiated a thread by using the constructor, since the thread is created from it. Then we can start by calling the start() method. Run the code in your editor to see how it works.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>A thread is a light-weight process in Java. It's a path of execution within a process. There are only two methods to create threads in Java.</p>
<p>In a browser, multiple tabs can be multiple threads. Once a thread is created it can be present in any of the states we discussed above.</p>
<p>Thank you for reading.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Multithreaded Python: Slithering Through an I/O Bottleneck? ]]>
                </title>
                <description>
                    <![CDATA[ How taking advantage of parallelism in Python can make your software orders of magnitude faster. I recently developed a project that I called Hydra: a multithreaded link checker written in Python. Unlike many Python site crawlers I found while resear... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/multithreaded-python/</link>
                <guid isPermaLink="false">66bd8f67621c718d60a31038</guid>
                
                    <category>
                        <![CDATA[ Computers ]]>
                    </category>
                
                    <category>
                        <![CDATA[ multithreading ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Victoria Drake ]]>
                </dc:creator>
                <pubDate>Sun, 01 Mar 2020 00:16:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/03/cover.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <h3 id="heading-how-taking-advantage-of-parallelism-in-python-can-make-your-software-orders-of-magnitude-faster">How taking advantage of parallelism in Python can make your software orders of magnitude faster.</h3>
<p>I recently developed a project that I called <a target="_blank" href="https://github.com/victoriadrake/hydra-link-checker">Hydra</a>: a multithreaded link checker written in Python. Unlike many Python site crawlers I found while researching, Hydra uses only standard libraries, with no external dependencies like BeautifulSoup. It’s intended to be run as part of a CI/CD process, so part of its success depended on being  fast.</p>
<p>Multiple threads in Python is a bit of a bitey subject (not sorry) in that the Python interpreter doesn’t actually let multiple threads execute at the same time. </p>
<p>Python’s <a target="_blank" href="https://wiki.python.org/moin/GlobalInterpreterLock">Global Interpreter Lock</a>, or GIL, prevents multiple threads from executing Python bytecodes at once. Each thread that wants to execute must first wait for the GIL to be released by the currently executing thread. The GIL is pretty much the microphone in a low-budget conference panel, except where no one gets to shout.</p>
<p>This has the advantage of preventing <a target="_blank" href="https://en.wikipedia.org/wiki/Race_condition">race conditions</a>. It does, however, lack the performance advantages afforded by running multiple tasks in parallel. (If you’d like a refresher on concurrency, parallelism, and multithreading, see <a target="_blank" href="https://victoria.dev/blog/concurrency-parallelism-and-the-many-threads-of-santa-claus/">Concurrency, parallelism, and the many threads of Santa Claus</a>.) </p>
<p>While I prefer Go for its convenient first-class primitives that support concurrency (see <a target="_blank" href="https://tour.golang.org/concurrency/1">Goroutines</a>), this project’s recipients were more comfortable with Python. I took it as an opportunity to test and explore!</p>
<p>Simultaneously performing multiple tasks in Python isn’t impossible; it just takes a little extra work. For Hydra, the main advantage is in overcoming the input/output (I/O) bottleneck.</p>
<p>In order to get web pages to check, Hydra needs to go out to the Internet and fetch them. When compared to tasks that are performed by the CPU alone, going out over the network is comparatively slower. How slow?</p>
<p>Here are approximate timings for tasks performed on a typical PC:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td></td><td>Task</td><td>Time</td></tr>
</thead>
<tbody>
<tr>
<td>CPU</td><td>execute typical instruction</td><td>1/1,000,000,000 sec = 1 nanosec</td></tr>
<tr>
<td>CPU</td><td>fetch from L1 cache memory</td><td>0.5 nanosec</td></tr>
<tr>
<td>CPU</td><td>branch misprediction</td><td>5 nanosec</td></tr>
<tr>
<td>CPU</td><td>fetch from L2 cache memory</td><td>7 nanosec</td></tr>
<tr>
<td>RAM</td><td>Mutex lock/unlock</td><td>25 nanosec</td></tr>
<tr>
<td>RAM</td><td>fetch from main memory</td><td>100 nanosec</td></tr>
<tr>
<td>Network</td><td>send 2K bytes over 1Gbps network</td><td>20,000 nanosec</td></tr>
<tr>
<td>RAM</td><td>read 1MB sequentially from memory</td><td>250,000 nanosec</td></tr>
<tr>
<td>Disk</td><td>fetch from new disk location (seek)</td><td>8,000,000 nanosec   (8ms)</td></tr>
<tr>
<td>Disk</td><td>read 1MB sequentially from disk</td><td>20,000,000 nanosec  (20ms)</td></tr>
<tr>
<td>Network</td><td>send packet US to Europe and back</td><td>150,000,000 nanosec (150ms)</td></tr>
</tbody>
</table>
</div><p>Peter Norvig first published these numbers some years ago in <a target="_blank" href="http://norvig.com/21-days.html#answers">Teach Yourself Programming in Ten Years</a>. Since computers and their components change year over year, the exact numbers shown above aren’t the point. What these numbers help to illustrate is the difference, in orders of magnitude, between operations.</p>
<p>Compare the difference between fetching from main memory and sending a simple packet over the Internet. While both these operations occur in less than the blink of an eye (literally) from a human perspective, you can see that sending a simple packet over the Internet is over a million times slower than fetching from RAM. It’s a difference that, in a single-thread program, can quickly accumulate to form troublesome bottlenecks.</p>
<p>In Hydra, the task of parsing response data and assembling results into a report is relatively fast, since it all happens on the CPU. The slowest portion of the program’s execution, by over six orders of magnitude, is network latency. Not only does Hydra need to fetch packets, but whole web pages! </p>
<p>One way of  improving Hydra’s performance is to find a way for the page fetching tasks to execute without blocking the main thread.</p>
<p>Python has a couple options for doing tasks in parallel: multiple processes, or multiple threads. These methods allow you to circumvent the GIL and speed up execution in a couple different ways.</p>
<h2 id="heading-multiple-processes">Multiple processes</h2>
<p>To execute parallel tasks using multiple processes, you can use Python’s <a target="_blank" href="https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ProcessPoolExecutor"><code>ProcessPoolExecutor</code></a>. A concrete subclass of <a target="_blank" href="https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor"><code>Executor</code></a> from the <a target="_blank" href="https://docs.python.org/3/library/concurrent.futures.html"><code>concurrent.futures</code> module</a>, <code>ProcessPoolExecutor</code> uses a pool of processes spawned with the <a target="_blank" href="https://docs.python.org/3/library/multiprocessing.html#module-multiprocessing"><code>multiprocessing</code> module</a> to avoid the GIL.</p>
<p>This option uses worker subprocesses that maximally default to the number of processors on the machine. The <code>multiprocessing</code> module allows you to maximally parallelize function execution across processes, which can really speed up compute-bound (or <a target="_blank" href="https://en.wikipedia.org/wiki/CPU-bound">CPU-bound</a>) tasks.</p>
<p>Since the main bottleneck for Hydra is I/O and not the processing to be done by the CPU, I’m better served by using multiple threads.</p>
<h2 id="heading-multiple-threads">Multiple threads</h2>
<p>Fittingly named, Python’s <a target="_blank" href="https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor"><code>ThreadPoolExecutor</code></a> uses a pool of threads to execute asynchronous tasks. Also a subclass of <a target="_blank" href="https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor"><code>Executor</code></a>, it uses a defined number of maximum worker threads (at least five by default, according to the formula <code>min(32, os.cpu_count() + 4)</code>) and reuses idle threads before starting new ones, making it pretty efficient.</p>
<p>Here is a snippet of Hydra with comments showing how Hydra uses <code>ThreadPoolExecutor</code> to achieve parallel multithreaded bliss:</p>
<pre><code class="lang-py"><span class="hljs-comment"># Create the Checker class</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Checker</span>:</span>
    <span class="hljs-comment"># Queue of links to be checked</span>
    TO_PROCESS = Queue()
    <span class="hljs-comment"># Maximum workers to run</span>
    THREADS = <span class="hljs-number">100</span>
    <span class="hljs-comment"># Maximum seconds to wait for HTTP response</span>
    TIMEOUT = <span class="hljs-number">60</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, url</span>):</span>
        ...
        <span class="hljs-comment"># Create the thread pool</span>
        self.pool = futures.ThreadPoolExecutor(max_workers=self.THREADS)


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">run</span>(<span class="hljs-params">self</span>):</span>
    <span class="hljs-comment"># Run until the TO_PROCESS queue is empty</span>
    <span class="hljs-keyword">while</span> <span class="hljs-literal">True</span>:
        <span class="hljs-keyword">try</span>:
            target_url = self.TO_PROCESS.get(block=<span class="hljs-literal">True</span>, timeout=<span class="hljs-number">2</span>)
            <span class="hljs-comment"># If we haven't already checked this link</span>
            <span class="hljs-keyword">if</span> target_url[<span class="hljs-string">"url"</span>] <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> self.visited:
                <span class="hljs-comment"># Mark it as visited</span>
                self.visited.add(target_url[<span class="hljs-string">"url"</span>])
                <span class="hljs-comment"># Submit the link to the pool</span>
                job = self.pool.submit(self.load_url, target_url, self.TIMEOUT)
                job.add_done_callback(self.handle_future)
        <span class="hljs-keyword">except</span> Empty:
            <span class="hljs-keyword">return</span>
        <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:
            print(e)
</code></pre>
<p>You can view the full code in <a target="_blank" href="https://github.com/victoriadrake/hydra-link-checker">Hydra’s GitHub repository</a>.</p>
<h2 id="heading-single-thread-to-multithread">Single thread to multithread</h2>
<p>If you’d like to see the full effect, I compared the run times for checking my website between a prototype single-thread program, and the multiheaded - I mean multithreaded - Hydra.</p>
<pre><code class="lang-text">time python3 slow-link-check.py https://victoria.dev

real    17m34.084s
user    11m40.761s
sys     0m5.436s


time python3 hydra.py https://victoria.dev

real    0m15.729s
user    0m11.071s
sys     0m2.526s
</code></pre>
<p>The single-thread program, which blocks on I/O, ran in about seventeen minutes. When I first ran the multithreaded version, it finished in 1m13.358s - after some profiling and tuning, it took a little under sixteen seconds. </p>
<p>Again, the exact times don’t mean all that much; they’ll vary depending on factors such as the size of the site being crawled, your network speed, and your program’s balance between the overhead of thread management and the benefits of  parallelism.</p>
<p>The more important thing, and the result I’ll take any day, is a program that runs some orders of magnitude faster.</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>
        
    </channel>
</rss>
