<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <title>Posts on Aamer Paul</title>
        <link>https://aamernabi.github.io/posts/</link>
        <description>Recent content in Posts on Aamer Paul</description>
        <generator>Hugo -- gohugo.io</generator>
        <language>en-us</language>
        <lastBuildDate>Sat, 04 Oct 2025 21:53:45 +0530</lastBuildDate>
        <atom:link href="https://aamernabi.github.io/posts/index.xml" rel="self" type="application/rss+xml" />
        
        <item>
            <title>Building an AI Email Assistant with Prompt Chaining and LangGraph</title>
            <link>https://aamernabi.github.io/posts/prompt-chaining-using-langgraph/</link>
            <pubDate>Sat, 04 Oct 2025 21:53:45 +0530</pubDate>
            
            <guid>https://aamernabi.github.io/posts/prompt-chaining-using-langgraph/</guid>
            <description>&lt;h2 id=&#34;introduction&#34;&gt;Introduction&lt;/h2&gt;
&lt;p&gt;Generative AI has unlocked solutions to problems previously considered impractical or even impossible to automate. Take email management, for example. The daily influx of client inquiries, meeting requests, and project updates, it can consume your entire workday. While simple AI solutions promise relief but they often fall short, generating generic and context-blind replies.&lt;/p&gt;
&lt;p&gt;In this article, we will move beyond  basic &amp;ldquo;one-shot&amp;rdquo; LLM prompts to build an intelligent email responder using &lt;strong&gt;Prompt Chaining&lt;/strong&gt;, &lt;strong&gt;Context Engineering&lt;/strong&gt;, and &lt;strong&gt;LangGraph&lt;/strong&gt; for robust orchestration. We will build a sophisticated multi-step workflow that:&lt;/p&gt;</description>
            <content type="html"><![CDATA[<h2 id="introduction">Introduction</h2>
<p>Generative AI has unlocked solutions to problems previously considered impractical or even impossible to automate. Take email management, for example. The daily influx of client inquiries, meeting requests, and project updates, it can consume your entire workday. While simple AI solutions promise relief but they often fall short, generating generic and context-blind replies.</p>
<p>In this article, we will move beyond  basic &ldquo;one-shot&rdquo; LLM prompts to build an intelligent email responder using <strong>Prompt Chaining</strong>, <strong>Context Engineering</strong>, and <strong>LangGraph</strong> for robust orchestration. We will build a sophisticated multi-step workflow that:</p>
<ol>
<li>Extracts <strong>intent</strong> and <strong>key information</strong> from an incoming email</li>
<li>Generates a <strong>structured outline</strong> for the response</li>
<li>Drafts the <strong>complete email body</strong></li>
<li>Rewrites the draft to match your <strong>desired tone</strong> (formal, friendly, etc.)</li>
</ol>
<p>By the end, you will have a clear understanding of how to decompose complex AI tasks into reliable workflows.</p>
<p>But before we dive into implementation, we need to understand what Prompt Chaining, Context Engineering, and LangGraph are.</p>
<h2 id="prompt-chaining">Prompt Chaining</h2>
<p>What is Prompt Chaining?</p>
<p><strong>Prompt chaining</strong> involves breaking down a complex task into a <strong>sequence of smaller, more manageable steps</strong>, with each
step handled by a separate LLM prompt. The output from one prompt then serves as the input for the subsequent prompt,
allowing the LLM to build a final solution incrementally. For example, one prompt could extract key entities from
a document, and a second prompt could then use these entities to generate a summary.</p>
<p><img src="/the_prompt_chaining_workflow.png" alt="The prompt chaining workflow">
<span style="font-size: 0.8em;"> Prompt chaining workflow </span>
</p>
<p>Prompt Chaining offers several advantages:</p>
<ul>
<li>
<p><strong>Improved Accuracy:</strong> The main advantage of the chaining prompts is that it allows iterative refinements, improving
accuracy of the final output. However the downside of this workflow is latency. It trade offs latency for higher accuracy.</p>
</li>
<li>
<p><strong>Scalability:</strong> Chaining prompts allow generation of long or detailed content by breaking down into smaller, and manageable parts.</p>
</li>
</ul>
<p><strong>Why Prompt Chaining Matters</strong></p>
<p>This approach ensures each step has a focused responsibility, making the system more reliable and debuggable than a single monolithic prompt.</p>
<p>Examples where prompt chaining can be useful:</p>
<ul>
<li><strong>Content Creation:</strong> Generating detailed articles, stories, or scripts by chaining related prompts.</li>
<li><strong>Language Translation:</strong> Translating text across multiple languages using a chain of prompts to ensure accuracy and fluency.</li>
</ul>
<h2 id="context-engineering">Context Engineering</h2>
<p>LLMs are stateless, meaning they don&rsquo;t retain memory of past interactions between calls. To get best results, we must provide an optimized <strong>context</strong> during each interaction.</p>
<p>Context refers to everything sent to the model in the prompt and can include:</p>
<ul>
<li>Instructions (what the model is supposed to do)</li>
<li>User input or questions</li>
<li>External data (RAG)</li>
<li>State or history (e.g., tool calls, results from previous tool calls or prior messages in a conversation)</li>
<li>Expected output structure (e.g., response format, schema, or constraints)</li>
</ul>
<p><strong>Context engineering</strong> is the process of curating, structuring, and managing the input (context window) provided to a language model in order to maximize its performance on a given task.</p>
<p><img src="/context-engineering-for-agents.png" alt="Context Engineering"></p>
<span style="font-size: 0.8em;"> Context Engineering </span>

<h2 id="langgraph">LangGraph</h2>
<p>In this article, we&rsquo;ll use LangGraph to build an intelligent email responder.</p>
<p>But what exactly is LangGraph?</p>
<p><strong>LangGraph</strong> is an open-source AI agent framework, for building, deploying, and managing complex AI Agentic systems.
It&rsquo;s a low-level framework for  building <strong>stateful</strong>, <strong>long-running</strong>, <strong>multi-actor</strong> agents and workflows.</p>
<p>Before we begin the implementation, let&rsquo;s first understand the core concepts behind LangGraph.</p>
<h3 id="core-concepts-of-langgraph">Core Concepts of LangGraph</h3>
<p>LangGraph is build on the concept of <strong>graph</strong>. In LangGraph, you build a graph, instead of linear chains (LangChain).
This makes LangGraph better for complex workflows eg: loops, branching, retries, multi-agent coordination</p>
<p>Following are the core concepts in LangGraph:</p>
<ol>
<li>
<p><strong>State</strong>:</p>
<ul>
<li>Unlike LangChain&rsquo;s memory, LangGraph uses a <strong>state object</strong> that is passed and updated as nodes run.</li>
<li>A state is a dictionary (<code>TypedDict</code>) of all variables your workflow needs. Its a data structure/context passed between steps.</li>
<li>Example:
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-python" data-lang="python"><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">State</span>(TypedDict):
</span></span><span style="display:flex;"><span>  question: str
</span></span><span style="display:flex;"><span>  classification: str <span style="color:#f92672">|</span> <span style="color:#66d9ef">None</span>
</span></span><span style="display:flex;"><span>  answer: str <span style="color:#f92672">|</span> <span style="color:#66d9ef">None</span>
</span></span></code></pre></div></li>
</ul>
</li>
<li>
<p><strong>Nodes</strong>:</p>
<ul>
<li>A node is a function that takes in state and returns the updates</li>
<li>Nodes can call LLMs, APIs, or some logic</li>
<li>Example:
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-python" data-lang="python"><span style="display:flex;"><span><span style="color:#66d9ef">def</span> <span style="color:#a6e22e">classify_node</span>(state):
</span></span><span style="display:flex;"><span>    q <span style="color:#f92672">=</span> state[<span style="color:#e6db74">&#34;question&#34;</span>]
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">if</span> <span style="color:#e6db74">&#34;hello&#34;</span> <span style="color:#f92672">in</span> q<span style="color:#f92672">.</span>lower():
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> {<span style="color:#e6db74">&#34;classification&#34;</span>: <span style="color:#e6db74">&#34;greeting&#34;</span>}
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> {<span style="color:#e6db74">&#34;classification&#34;</span>: <span style="color:#e6db74">&#34;question&#34;</span>}
</span></span></code></pre></div></li>
</ul>
</li>
<li>
<p><strong>Edges</strong>:</p>
<ul>
<li>Edges connect nodes</li>
<li>They can be <strong>fixed</strong> (always go A → B) or <strong>conditional</strong> (branch depending on state)</li>
<li>LangGraph supports Control Flow:
<ul>
<li><em>Branching</em>: if condition X, go to Node &lsquo;A&rsquo;; else, go to Node &lsquo;B&rsquo;</li>
<li><em>Loops</em>: repeat until condition met (retry, re-ask user, refine)</li>
<li><em>Parallel</em>: run multiple nodes on a list and merge (map-reduce)</li>
</ul>
</li>
</ul>
</li>
<li>
<p><strong>Tools</strong>:</p>
<ul>
<li>Tool is a function or action that your agents can use to get something done like calling an API, doing a calculation, searching a database, or accessing a file.</li>
<li>Think of tools as <strong>skills</strong> or <strong>abilities</strong> that you give your agent.</li>
</ul>
</li>
<li>
<p><strong>Durable execution &amp; Checkpointing</strong>:</p>
<ul>
<li>LangGraph can pause and resume workflows</li>
<li>Useful for long-running agents or workflows with <a href="https://docs.langchain.com/oss/python/langgraph/add-human-in-the-loop">human approval</a></li>
</ul>
</li>
<li>
<p><strong>StateGraph</strong>:</p>
<ul>
<li>A graph that connects nodes and edges together</li>
<li>A StateGraph is a flowchart of steps (nodes) your AI agent goes through to complete a task</li>
</ul>
</li>
</ol>
<h3 id="setting-up-langgraph">Setting up LangGraph</h3>
<p>This section will guide you through the process of installing and configuring LangGraph in your development environment.</p>
<ul>
<li>
<p>First ensure that <code>Python 3.12</code> or later is installed on your machine</p>
</li>
<li>
<p>Create a Virtual Environment</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-bash" data-lang="bash"><span style="display:flex;"><span>python -m venv .
</span></span><span style="display:flex;"><span>source langgraph_env/bin/activate 
</span></span></code></pre></div></li>
<li>
<p>Install LangGraph dependencies</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-bash" data-lang="bash"><span style="display:flex;"><span>pip install langgraph python-dotenv
</span></span><span style="display:flex;"><span>pip install langchain-openai   <span style="color:#75715e"># integration package</span>
</span></span></code></pre></div><p>Set environment variable <code>OPENAI_API_KEY</code>.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-bash" data-lang="bash"><span style="display:flex;"><span>export OPENAI_API_KEY<span style="color:#f92672">=</span><span style="color:#e6db74">&#34;your-api-key&#34;</span>
</span></span></code></pre></div></li>
<li>
<p>Verify Installation</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-python" data-lang="python"><span style="display:flex;"><span><span style="color:#f92672">import</span> langgraph
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>print(langgraph<span style="color:#f92672">.</span>__version__)
</span></span></code></pre></div></li>
</ul>
<h2 id="implementation-building-email-assistant-step-by-step">Implementation: Building Email Assistant Step by Step</h2>
<p>Now that we understand the core concepts, let&rsquo;s start building AI Email Assistant using LangGraph. We&rsquo;ll model the email response process as a structured pipeline where each step builds upon the previous one.</p>
<h3 id="defining-processing-pipeline">Defining Processing Pipeline</h3>
<p>Our AI assistant will transform incoming emails into thoughtful responses through four distinct stages:</p>
<ul>
<li>Input: Raw email text</li>
<li>Step 1: Extract key information and intent</li>
<li>Step 2: Generate a structured response outline</li>
<li>Step 3: Draft the complete email body</li>
<li>Step 4: Apply tone transformation (professional, friendly, casual, etc.)</li>
<li>Output: Polished, context-aware email response</li>
</ul>
<p>The chain will look like following</p>
<p><strong>Chain:</strong></p>
<ol>
<li>Prompt 1 → &ldquo;Extract intent and key info from incoming email&rdquo;</li>
<li>Prompt 2 → &ldquo;Generate a response outline&rdquo;</li>
<li>Prompt 3 → &ldquo;Draft complete email body&rdquo;</li>
<li>Prompt 4 (Optional) → &ldquo;Apply tone transformation (professional, friendly, casual, etc.)&rdquo;</li>
</ol>
<p><img src="/langgraph-graph-graph_api_example.png" alt="Example"></p>
<h3 id="implementation">Implementation</h3>
<ol>
<li>
<p>Lets first define the tools and the model</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-python" data-lang="python"><span style="display:flex;"><span>load_dotenv()
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">@tool</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">def</span> <span style="color:#a6e22e">last_unread_email</span>() <span style="color:#f92672">-&gt;</span> str:
</span></span><span style="display:flex;"><span>    <span style="color:#75715e"># your logic to retrieve last unread email</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> <span style="color:#e6db74">&#34;&#34;&#34;
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    From: adam@example.com
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    Date: 2024, Dec 12 14:00
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    Subject: Bulk Order Inquiry
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    Hi Neha,
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    I’m reaching out to inquire about the availability of your product in bulk.
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    We are looking to order around 500 units and would like to know the pricing and delivery timeline.
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    Please get back to me by the end of the week.
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    Best Regards,
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    Adam Willson
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    &#34;&#34;&#34;</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>tools <span style="color:#f92672">=</span> [last_unread_email]
</span></span><span style="display:flex;"><span>tools_by_name <span style="color:#f92672">=</span> {tool<span style="color:#f92672">.</span>name: tool <span style="color:#66d9ef">for</span> tool <span style="color:#f92672">in</span> tools}
</span></span><span style="display:flex;"><span>llm <span style="color:#f92672">=</span> init_chat_model(model<span style="color:#f92672">=</span>os<span style="color:#f92672">.</span>getenv(<span style="color:#e6db74">&#34;MODEL_NAME&#34;</span>), model_provider<span style="color:#f92672">=</span>os<span style="color:#f92672">.</span>getenv(<span style="color:#e6db74">&#34;MODEL_PROVIDER&#34;</span>), temperature<span style="color:#f92672">=</span><span style="color:#ae81ff">0</span>)
</span></span></code></pre></div><p>Make sure to add .env file with two variables:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-properties" data-lang="properties"><span style="display:flex;"><span><span style="color:#a6e22e">MODEL_PROVIDER</span><span style="color:#f92672">=</span><span style="color:#e6db74">&lt;model-provider&gt;</span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">MODEL_NAME</span><span style="color:#f92672">=</span><span style="color:#e6db74">&lt;model-name&gt;</span>
</span></span></code></pre></div></li>
<li>
<p>Next, we define the state, which will consist of five fields:</p>
<ul>
<li><code>**email_text**</code>: Represents the raw incoming email content.</li>
<li><code>**extraction**</code>: A structured model that extracts the email’s intent, tone, questions, and urgency.</li>
<li><code>**reply_outline**</code>: A preliminary outline for drafting a response.</li>
<li><code>**full_email**</code>: The body of the drafted response.</li>
<li><code>**final_polished_email**</code>: The polished version of the email ready for sending.</li>
</ul>
<p>At each stage of processing, the state will be used and updated by the nodes.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-python" data-lang="python"><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">EmailIntentExtraction</span>(BaseModel):
</span></span><span style="display:flex;"><span>    intent: str
</span></span><span style="display:flex;"><span>    questions: list[str]
</span></span><span style="display:flex;"><span>    tone: str
</span></span><span style="display:flex;"><span>    urgency: str
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">@classmethod</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">def</span> <span style="color:#a6e22e">empty</span>(cls) <span style="color:#f92672">-&gt;</span> <span style="color:#e6db74">&#34;EmailIntentExtraction&#34;</span>:
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> EmailIntentExtraction(intent<span style="color:#f92672">=</span><span style="color:#e6db74">&#34;&#34;</span>, questions<span style="color:#f92672">=</span>[], tone<span style="color:#f92672">=</span><span style="color:#e6db74">&#34;&#34;</span>, urgency<span style="color:#f92672">=</span><span style="color:#e6db74">&#34;&#34;</span>)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">State</span>(TypedDict):
</span></span><span style="display:flex;"><span>    email_text: str
</span></span><span style="display:flex;"><span>    extraction: EmailIntentExtraction
</span></span><span style="display:flex;"><span>    reply_outline: str
</span></span><span style="display:flex;"><span>    full_email: str
</span></span><span style="display:flex;"><span>    final_polished_email: str
</span></span></code></pre></div></li>
<li>
<p>The next step is to define the nodes, which can be call to LLM (Large Language Model), external APIs, or custom logic.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-python" data-lang="python"><span style="display:flex;"><span><span style="color:#66d9ef">def</span> <span style="color:#a6e22e">get_last_unread_email</span>(state: State) <span style="color:#f92672">-&gt;</span> dict[str, Any]:
</span></span><span style="display:flex;"><span>    llm_with_tools <span style="color:#f92672">=</span> llm<span style="color:#f92672">.</span>bind_tools(tools)
</span></span><span style="display:flex;"><span>    message <span style="color:#f92672">=</span> llm_with_tools<span style="color:#f92672">.</span>invoke(
</span></span><span style="display:flex;"><span>        [
</span></span><span style="display:flex;"><span>            SystemMessage(content<span style="color:#f92672">=</span><span style="color:#e6db74">&#34;You are a helpful assistant that can get unread emails.&#34;</span>),
</span></span><span style="display:flex;"><span>            HumanMessage(content<span style="color:#f92672">=</span><span style="color:#e6db74">&#34;Get last unread mail from inbox&#34;</span>),
</span></span><span style="display:flex;"><span>        ]
</span></span><span style="display:flex;"><span>    )
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e"># unnecessary: message is of type BaseMessage</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">if</span> <span style="color:#f92672">not</span> isinstance(message, AIMessage):
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> {}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    result <span style="color:#f92672">=</span> []
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">if</span> message<span style="color:#f92672">.</span>tool_calls:
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">for</span> tool_call <span style="color:#f92672">in</span> message<span style="color:#f92672">.</span>tool_calls:
</span></span><span style="display:flex;"><span>            tool <span style="color:#f92672">=</span> tools_by_name[tool_call[<span style="color:#e6db74">&#34;name&#34;</span>]]
</span></span><span style="display:flex;"><span>            tool_result <span style="color:#f92672">=</span> tool<span style="color:#f92672">.</span>invoke(tool_call[<span style="color:#e6db74">&#34;args&#34;</span>])
</span></span><span style="display:flex;"><span>            result<span style="color:#f92672">.</span>append(tool_result)
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">else</span>:
</span></span><span style="display:flex;"><span>        result<span style="color:#f92672">.</span>append(message<span style="color:#f92672">.</span>content)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> {<span style="color:#e6db74">&#34;email_text&#34;</span>: <span style="color:#e6db74">&#34;</span><span style="color:#ae81ff">\n</span><span style="color:#e6db74">&#34;</span><span style="color:#f92672">.</span>join(result)}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">def</span> <span style="color:#a6e22e">extract_intent_key_info</span>(state: State) <span style="color:#f92672">-&gt;</span> dict[str, Any]:
</span></span><span style="display:flex;"><span>    extraction_prompt <span style="color:#f92672">=</span> <span style="color:#e6db74">f</span><span style="color:#e6db74">&#34;&#34;&#34;
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    Extract the following information from the email below:
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    1. Sender&#39;s intent
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    2. Specific questions or requests
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    3. Tone of the email
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    4. Urgency or deadline
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    Email:
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    </span><span style="color:#ae81ff">\&#34;\&#34;\&#34;</span><span style="color:#e6db74">
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    </span><span style="color:#e6db74">{</span>state[<span style="color:#e6db74">&#34;email_text&#34;</span>]<span style="color:#e6db74">}</span><span style="color:#e6db74">
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    </span><span style="color:#ae81ff">\&#34;\&#34;\&#34;</span><span style="color:#e6db74">
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    Respond in JSON format.
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    &#34;&#34;&#34;</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    llm_with_structured_output <span style="color:#f92672">=</span> llm<span style="color:#f92672">.</span>with_structured_output(EmailIntentExtraction)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    message <span style="color:#f92672">=</span> llm_with_structured_output<span style="color:#f92672">.</span>invoke(
</span></span><span style="display:flex;"><span>        [
</span></span><span style="display:flex;"><span>            SystemMessage(content<span style="color:#f92672">=</span><span style="color:#e6db74">&#34;You are a helpful assistant that extracts structured data from emails.&#34;</span>),
</span></span><span style="display:flex;"><span>            HumanMessage(content<span style="color:#f92672">=</span>extraction_prompt),
</span></span><span style="display:flex;"><span>        ]
</span></span><span style="display:flex;"><span>    )
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> {<span style="color:#e6db74">&#34;extraction&#34;</span>: message}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">def</span> <span style="color:#a6e22e">generate_reply_outline</span>(state: State) <span style="color:#f92672">-&gt;</span> dict[str, Any]:
</span></span><span style="display:flex;"><span>    extracted_info: EmailIntentExtraction <span style="color:#f92672">=</span> state[<span style="color:#e6db74">&#34;extraction&#34;</span>]
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    outline_prompt <span style="color:#f92672">=</span> <span style="color:#e6db74">f</span><span style="color:#e6db74">&#34;&#34;&#34;
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    You are an email assistant.
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    Based on the following extracted info, generate a structured email **outline** with these parts:
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    1. Greeting
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    2. Acknowledgment of the sender&#39;s intent
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    3. Answers to questions or information needed
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    4. Next steps or follow-up
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    5. Closing
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    Make sure the tone is </span><span style="color:#e6db74">{</span>extracted_info<span style="color:#f92672">.</span>tone<span style="color:#e6db74">}</span><span style="color:#e6db74"> and mention that a response will be sent before
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    </span><span style="color:#e6db74">{</span>extracted_info<span style="color:#f92672">.</span>urgency<span style="color:#f92672">.</span>lower()<span style="color:#e6db74">}</span><span style="color:#e6db74">.
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    Extracted Info:
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    </span><span style="color:#e6db74">{</span>extracted_info<span style="color:#f92672">.</span>model_dump_json()<span style="color:#e6db74">}</span><span style="color:#e6db74">
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    &#34;&#34;&#34;</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    message <span style="color:#f92672">=</span> llm<span style="color:#f92672">.</span>invoke(
</span></span><span style="display:flex;"><span>        [
</span></span><span style="display:flex;"><span>            SystemMessage(
</span></span><span style="display:flex;"><span>                content<span style="color:#f92672">=</span><span style="color:#e6db74">&#34;You are a helpful assistant that generates email outlines based on extracted intent.&#34;</span>
</span></span><span style="display:flex;"><span>            ),
</span></span><span style="display:flex;"><span>            HumanMessage(content<span style="color:#f92672">=</span>outline_prompt),
</span></span><span style="display:flex;"><span>        ]
</span></span><span style="display:flex;"><span>    )
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> {<span style="color:#e6db74">&#34;reply_outline&#34;</span>: message<span style="color:#f92672">.</span>content}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">def</span> <span style="color:#a6e22e">generate_full_reply_email</span>(state: State) <span style="color:#f92672">-&gt;</span> dict[str, Any]:
</span></span><span style="display:flex;"><span>    email_outline <span style="color:#f92672">=</span> state[<span style="color:#e6db74">&#34;reply_outline&#34;</span>]
</span></span><span style="display:flex;"><span>    compose_prompt <span style="color:#f92672">=</span> <span style="color:#e6db74">f</span><span style="color:#e6db74">&#34;&#34;&#34;
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    Using the following email outline, write a professional and polite email reply.
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    Format it as a formal business email. Keep the tone professional.
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    Outline:
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    </span><span style="color:#e6db74">{</span>email_outline<span style="color:#e6db74">}</span><span style="color:#e6db74">
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    &#34;&#34;&#34;</span>
</span></span><span style="display:flex;"><span>    message <span style="color:#f92672">=</span> llm<span style="color:#f92672">.</span>invoke(
</span></span><span style="display:flex;"><span>        [
</span></span><span style="display:flex;"><span>            SystemMessage(content<span style="color:#f92672">=</span><span style="color:#e6db74">&#34;You are an AI that writes professional business emails based on outlines.&#34;</span>),
</span></span><span style="display:flex;"><span>            HumanMessage(content<span style="color:#f92672">=</span>compose_prompt),
</span></span><span style="display:flex;"><span>        ]
</span></span><span style="display:flex;"><span>    )
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> {<span style="color:#e6db74">&#34;full_email&#34;</span>: message<span style="color:#f92672">.</span>content}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">def</span> <span style="color:#a6e22e">__get_rewrite_prompt</span>(email_text: str, tone: Literal[<span style="color:#e6db74">&#34;friendly&#34;</span>, <span style="color:#e6db74">&#34;formal&#34;</span>, <span style="color:#e6db74">&#34;casual&#34;</span>, <span style="color:#e6db74">&#34;firm&#34;</span>]):
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> <span style="color:#e6db74">f</span><span style="color:#e6db74">&#34;&#34;&#34;
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    Rewrite the following email in a more **</span><span style="color:#e6db74">{</span>tone<span style="color:#e6db74">}</span><span style="color:#e6db74">** tone.
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    Keep all the original information intact, but adapt the language to fit the new tone.
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    Email:
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    </span><span style="color:#ae81ff">\&#34;\&#34;\&#34;</span><span style="color:#e6db74">
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    </span><span style="color:#e6db74">{</span>email_text<span style="color:#e6db74">}</span><span style="color:#e6db74">
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    </span><span style="color:#ae81ff">\&#34;\&#34;\&#34;</span><span style="color:#e6db74">
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    &#34;&#34;&#34;</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">def</span> <span style="color:#a6e22e">tone_rewriter</span>(state: State) <span style="color:#f92672">-&gt;</span> dict[str, Any]:
</span></span><span style="display:flex;"><span>    full_email <span style="color:#f92672">=</span> state[<span style="color:#e6db74">&#34;full_email&#34;</span>]
</span></span><span style="display:flex;"><span>    prompt <span style="color:#f92672">=</span> __get_rewrite_prompt(full_email, <span style="color:#e6db74">&#34;formal&#34;</span>)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    message <span style="color:#f92672">=</span> llm<span style="color:#f92672">.</span>invoke(
</span></span><span style="display:flex;"><span>        [
</span></span><span style="display:flex;"><span>            SystemMessage(
</span></span><span style="display:flex;"><span>                content<span style="color:#f92672">=</span>(
</span></span><span style="display:flex;"><span>                    <span style="color:#e6db74">&#34;You are an assistant that rewrites emails in different tones while keeping the original meaning.&#34;</span>
</span></span><span style="display:flex;"><span>                )
</span></span><span style="display:flex;"><span>            ),
</span></span><span style="display:flex;"><span>            HumanMessage(content<span style="color:#f92672">=</span>prompt),
</span></span><span style="display:flex;"><span>        ]
</span></span><span style="display:flex;"><span>    )
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> {<span style="color:#e6db74">&#34;final_polished_email&#34;</span>: message<span style="color:#f92672">.</span>content}
</span></span></code></pre></div></li>
<li>
<p>Next, define the logic to determine whether to end the process (Conditional Gate). For example, you can check if the email contains at least 100 characters. You can also customize this logic to suit your specific requirements.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-python" data-lang="python"><span style="display:flex;"><span><span style="color:#66d9ef">def</span> <span style="color:#a6e22e">validate_incoming_email</span>(state: State) <span style="color:#f92672">-&gt;</span> str:
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">if</span> len(state[<span style="color:#e6db74">&#34;email_text&#34;</span>]<span style="color:#f92672">.</span>strip()) <span style="color:#f92672">&gt;=</span> <span style="color:#ae81ff">100</span>:
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#e6db74">&#34;extract_intent_key_info&#34;</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> END
</span></span></code></pre></div></li>
<li>
<p>Build workflow</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-python" data-lang="python"><span style="display:flex;"><span><span style="color:#75715e"># Build workflow</span>
</span></span><span style="display:flex;"><span>workflow <span style="color:#f92672">=</span> StateGraph(State)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e"># Add nodes</span>
</span></span><span style="display:flex;"><span>workflow<span style="color:#f92672">.</span>add_node(<span style="color:#e6db74">&#34;get_last_unread_email&#34;</span>, get_last_unread_email)
</span></span><span style="display:flex;"><span>workflow<span style="color:#f92672">.</span>add_node(<span style="color:#e6db74">&#34;extract_intent_key_info&#34;</span>, extract_intent_key_info)
</span></span><span style="display:flex;"><span>workflow<span style="color:#f92672">.</span>add_node(<span style="color:#e6db74">&#34;generate_reply_outline&#34;</span>, generate_reply_outline)
</span></span><span style="display:flex;"><span>workflow<span style="color:#f92672">.</span>add_node(<span style="color:#e6db74">&#34;generate_full_reply_email&#34;</span>, generate_full_reply_email)
</span></span><span style="display:flex;"><span>workflow<span style="color:#f92672">.</span>add_node(<span style="color:#e6db74">&#34;tone_rewriter&#34;</span>, tone_rewriter)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e"># Add edges to connect nodes</span>
</span></span><span style="display:flex;"><span>workflow<span style="color:#f92672">.</span>add_edge(START, <span style="color:#e6db74">&#34;get_last_unread_email&#34;</span>)
</span></span><span style="display:flex;"><span>workflow<span style="color:#f92672">.</span>add_conditional_edges(<span style="color:#e6db74">&#34;get_last_unread_email&#34;</span>, validate_incoming_email, [<span style="color:#e6db74">&#34;extract_intent_key_info&#34;</span>, END])
</span></span><span style="display:flex;"><span>workflow<span style="color:#f92672">.</span>add_edge(<span style="color:#e6db74">&#34;extract_intent_key_info&#34;</span>, <span style="color:#e6db74">&#34;generate_reply_outline&#34;</span>)
</span></span><span style="display:flex;"><span>workflow<span style="color:#f92672">.</span>add_edge(<span style="color:#e6db74">&#34;generate_reply_outline&#34;</span>, <span style="color:#e6db74">&#34;generate_full_reply_email&#34;</span>)
</span></span><span style="display:flex;"><span>workflow<span style="color:#f92672">.</span>add_edge(<span style="color:#e6db74">&#34;generate_full_reply_email&#34;</span>, <span style="color:#e6db74">&#34;tone_rewriter&#34;</span>)
</span></span><span style="display:flex;"><span>workflow<span style="color:#f92672">.</span>add_edge(<span style="color:#e6db74">&#34;tone_rewriter&#34;</span>, END)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>chain <span style="color:#f92672">=</span> workflow<span style="color:#f92672">.</span>compile()
</span></span></code></pre></div></li>
<li>
<p>Invoke the workflow</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-python" data-lang="python"><span style="display:flex;"><span>initial_state <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#e6db74">&#34;email_text&#34;</span>: <span style="color:#e6db74">&#34;&#34;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#e6db74">&#34;extraction&#34;</span>: EmailIntentExtraction<span style="color:#f92672">.</span>empty(),
</span></span><span style="display:flex;"><span>    <span style="color:#e6db74">&#34;reply_outline&#34;</span>: <span style="color:#e6db74">&#34;&#34;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#e6db74">&#34;full_email&#34;</span>: <span style="color:#e6db74">&#34;&#34;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#e6db74">&#34;final_polished_email&#34;</span>: <span style="color:#e6db74">&#34;&#34;</span>,
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>messages <span style="color:#f92672">=</span> chain<span style="color:#f92672">.</span>invoke(initial_state)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">for</span> key <span style="color:#f92672">in</span> messages:
</span></span><span style="display:flex;"><span>    print(<span style="color:#e6db74">f</span><span style="color:#e6db74">&#34;</span><span style="color:#e6db74">{</span>key<span style="color:#e6db74">}</span><span style="color:#e6db74">: &#34;</span>)
</span></span><span style="display:flex;"><span>    print(messages[key])
</span></span><span style="display:flex;"><span>    print(<span style="color:#e6db74">&#34;---------------------------------------------&#34;</span>)
</span></span></code></pre></div></li>
<li>
<p>Test</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-python" data-lang="python"><span style="display:flex;"><span><span style="color:#75715e"># Input emails</span>
</span></span><span style="display:flex;"><span>input_email <span style="color:#f92672">=</span> <span style="color:#e6db74">&#34;&#34;&#34;
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">From: adam@example.com
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">Date: 2024, Dec 12 14:00
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">Subject: Bulk Order Inquiry
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">Hi Neha,
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">I’m reaching out to inquire about the availability of your product in bulk.
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">We are looking to order around 500 units and would like to know the pricing and delivery timeline.
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">Please get back to me by the end of the week.
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">Best Regards,
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">Adam Willson
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">&#34;&#34;&#34;</span>
</span></span></code></pre></div><p>Response (tone &ldquo;formal&rdquo;)</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-bash" data-lang="bash"><span style="display:flex;"><span>extraction:
</span></span><span style="display:flex;"><span>intent<span style="color:#f92672">=</span><span style="color:#e6db74">&#39;Inquiring about bulk order&#39;</span> questions<span style="color:#f92672">=[</span><span style="color:#e6db74">&#39;What is the pricing for 500 units?&#39;</span>, <span style="color:#e6db74">&#39;What is the delivery timeline for 500 units?&#39;</span><span style="color:#f92672">]</span> tone<span style="color:#f92672">=</span><span style="color:#e6db74">&#39;Professional&#39;</span> urgency<span style="color:#f92672">=</span><span style="color:#e6db74">&#39;End of the week&#39;</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>---------------------------------------------
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>reply_outline:
</span></span><span style="display:flex;"><span>Here is an email outline based on the information provided:
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>**Subject: Re: Bulk Order Inquiry - <span style="color:#ae81ff">500</span> Units**
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>1.  **Greeting**
</span></span><span style="display:flex;"><span>    *   Dear <span style="color:#f92672">[</span>Sender Name<span style="color:#f92672">]</span>,
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>2.  **Acknowledgment of Sender<span style="color:#960050;background-color:#1e0010">&#39;</span>s Intent**
</span></span><span style="display:flex;"><span>    *   Thank you <span style="color:#66d9ef">for</span> reaching out to us regarding your interest in a bulk order. We appreciate you considering our products.
</span></span><span style="display:flex;"><span>    *   We understand you are specifically inquiring about the pricing and delivery timeline <span style="color:#66d9ef">for</span> <span style="color:#ae81ff">500</span> units.
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>3.  **Answers to Questions / Information Needed**
</span></span><span style="display:flex;"><span>    *   We are currently compiling the detailed information regarding the pricing structure <span style="color:#66d9ef">for</span> <span style="color:#ae81ff">500</span> units and the estimated delivery timeline.
</span></span><span style="display:flex;"><span>    *   Please be assured that we will send a comprehensive response addressing both of your questions before the end of the week.
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>4.  **Next Steps / Follow-up**
</span></span><span style="display:flex;"><span>    *   We look forward to providing you with the necessary details and assisting you further with your bulk order.
</span></span><span style="display:flex;"><span>    *   Should you have any additional questions in the meantime, please <span style="color:#66d9ef">do</span> not hesitate to contact us.
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>5.  **Closing**
</span></span><span style="display:flex;"><span>    *   Sincerely,
</span></span><span style="display:flex;"><span>    *   <span style="color:#f92672">[</span>Your Name/Company Name<span style="color:#f92672">]</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>---------------------------------------------
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>full_email: 
</span></span><span style="display:flex;"><span>Subject: Re: Bulk Order Inquiry - <span style="color:#ae81ff">500</span> Units
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>Dear <span style="color:#f92672">[</span>Sender Name<span style="color:#f92672">]</span>,
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>Thank you <span style="color:#66d9ef">for</span> reaching out to us regarding your interest in a bulk order. We appreciate you considering our products and understand you are specifically inquiring about the pricing and delivery timeline <span style="color:#66d9ef">for</span> <span style="color:#ae81ff">500</span> units.
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>We are currently compiling the detailed information regarding the pricing structure <span style="color:#66d9ef">for</span> <span style="color:#ae81ff">500</span> units and the estimated delivery timeline. Please be assured that we will send a comprehensive response addressing both of your questions before the end of the week.
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>We look forward to providing you with the necessary details and assisting you further with your bulk order. Should you have any additional questions in the meantime, please <span style="color:#66d9ef">do</span> not hesitate to contact us.
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>Sincerely,
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#f92672">[</span>Your Name/Company Name<span style="color:#f92672">]</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>---------------------------------------------
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>final_polished_email: 
</span></span><span style="display:flex;"><span>Subject: Re: Bulk Order Inquiry - <span style="color:#ae81ff">500</span> Units
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>Dear <span style="color:#f92672">[</span>Sender Name<span style="color:#f92672">]</span>,
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>We acknowledge receipt of your inquiry regarding a bulk order. We appreciate your interest in our products and note your specific request concerning the pricing and estimated delivery timeline <span style="color:#66d9ef">for</span> <span style="color:#ae81ff">500</span> units.
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>We are currently in the process of compiling the comprehensive details pertaining to the pricing structure <span style="color:#66d9ef">for</span> <span style="color:#ae81ff">500</span> units and the projected delivery schedule. Please be advised that a comprehensive response addressing both of your inquiries will be dispatched prior to the close of this week.
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>We anticipate furnishing you with the requisite details and offering further assistance with your bulk order. Should you require any additional information or have further questions in the interim, please <span style="color:#66d9ef">do</span> not hesitate to contact us.
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>Sincerely,
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#f92672">[</span>Your Name/Company Name<span style="color:#f92672">]</span>
</span></span><span style="display:flex;"><span>---------------------------------------------
</span></span></code></pre></div></li>
</ol>
<h2 id="conclusion">Conclusion</h2>
<p>In this article, we&rsquo;ve built a sophisticated AI Email Assistant that demonstrates the power of modern LLM orchestration. By decomposing the complex task of email response into manageable steps using <strong>Prompt Chaining</strong>, we created a system that is more reliable, and effective than a single monolithic prompt.</p>
<p>This approach doesn&rsquo;t just apply to email assistants, the same pattern can be applied to countless other AI applications, from customer support systems to content generation pipelines.</p>
]]></content>
        </item>
        
        <item>
            <title>Strategy Pattern in Action</title>
            <link>https://aamernabi.github.io/posts/strategy-design-pattern-with-example/</link>
            <pubDate>Sat, 02 Aug 2025 08:53:20 +0530</pubDate>
            
            <guid>https://aamernabi.github.io/posts/strategy-design-pattern-with-example/</guid>
            <description>&lt;p&gt;&lt;strong&gt;Strategy Pattern&lt;/strong&gt; is a behavioral design pattern that enables selecting an algorithm’s behavior at runtime.&lt;/p&gt;
&lt;p&gt;It&amp;rsquo;s widely used and very flexible, perfect for cases where you want to avoid complex &lt;code&gt;if-else&lt;/code&gt; or &lt;code&gt;switch&lt;/code&gt; statements.&lt;/p&gt;
&lt;h3 id=&#34;use-cases&#34;&gt;Use cases&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;You want to replace conditionals (&lt;code&gt;if-else&lt;/code&gt; or &lt;code&gt;switch&lt;/code&gt;) with &lt;strong&gt;polymorphism&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;You need to switch behavior at runtime or make it configurable. Example: User selecting payment option&lt;/li&gt;
&lt;li&gt;You want to define multiple ways of doing something (e.g., sorting, compression, payment).&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&#34;core-concepts&#34;&gt;Core Concepts&lt;/h3&gt;
&lt;p&gt;The pattern consists of three main components:&lt;/p&gt;</description>
            <content type="html"><![CDATA[<p><strong>Strategy Pattern</strong> is a behavioral design pattern that enables selecting an algorithm’s behavior at runtime.</p>
<p>It&rsquo;s widely used and very flexible, perfect for cases where you want to avoid complex <code>if-else</code> or <code>switch</code> statements.</p>
<h3 id="use-cases">Use cases</h3>
<ul>
<li>You want to replace conditionals (<code>if-else</code> or <code>switch</code>) with <strong>polymorphism</strong>.</li>
<li>You need to switch behavior at runtime or make it configurable. Example: User selecting payment option</li>
<li>You want to define multiple ways of doing something (e.g., sorting, compression, payment).</li>
</ul>
<h3 id="core-concepts">Core Concepts</h3>
<p>The pattern consists of three main components:</p>
<ol>
<li>
<p><strong>Strategy</strong>: An interface or abstract class that defines a common method for all concrete strategies. The <strong>context</strong> uses this interface to call the algorithm.</p>
</li>
<li>
<p><strong>Concrete Strategy</strong>: The classes that implement the <code>Strategy</code> interface. Each class provides a specific implementation of the algorithm.</p>
</li>
<li>
<p><strong>Context</strong>: The class that holds a reference to a Strategy object. It uses the strategy&rsquo;s method to perform a certain action. The context is unaware of the concrete strategy being used, it only interacts with the Strategy interface.</p>
</li>
</ol>
<h3 id="example">Example</h3>
<p>Payment Strategy</p>
<ol>
<li>Strategy Interface</li>
</ol>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">PaymentStrategy</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">pay</span>(<span style="color:#66d9ef">double</span> amount);
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><ol start="2">
<li>Concrete Strategies</li>
</ol>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">CreditCardPayment</span> <span style="color:#66d9ef">implements</span> PaymentStrategy {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">@Override</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">pay</span>(<span style="color:#66d9ef">double</span> amount) {
</span></span><span style="display:flex;"><span>        System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(<span style="color:#e6db74">&#34;Paid $&#34;</span> <span style="color:#f92672">+</span> amount <span style="color:#f92672">+</span> <span style="color:#e6db74">&#34; using Credit Card.&#34;</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">PayPalPayment</span> <span style="color:#66d9ef">implements</span> PaymentStrategy {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">@Override</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">pay</span>(<span style="color:#66d9ef">double</span> amount) {
</span></span><span style="display:flex;"><span>        System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(<span style="color:#e6db74">&#34;Paid $&#34;</span> <span style="color:#f92672">+</span> amount <span style="color:#f92672">+</span> <span style="color:#e6db74">&#34; using PayPal.&#34;</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">CryptoPayment</span> <span style="color:#66d9ef">implements</span> PaymentStrategy {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">@Override</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">pay</span>(<span style="color:#66d9ef">double</span> amount) {
</span></span><span style="display:flex;"><span>        System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(<span style="color:#e6db74">&#34;Paid $&#34;</span> <span style="color:#f92672">+</span> amount <span style="color:#f92672">+</span> <span style="color:#e6db74">&#34; using Cryptocurrency.&#34;</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><ol start="3">
<li>Context Class</li>
</ol>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">PaymentContext</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> PaymentStrategy strategy;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">PaymentContext</span>() {}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// optional - for example you want to provide default strategy </span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">PaymentContext</span>(PaymentStrategy strategy) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">strategy</span> <span style="color:#f92672">=</span> strategy
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Strategy can be changed at runtime</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">setStrategy</span>(PaymentStrategy strategy) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">strategy</span> <span style="color:#f92672">=</span> strategy;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">payAmount</span>(<span style="color:#66d9ef">double</span> amount) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (strategy <span style="color:#f92672">==</span> <span style="color:#66d9ef">null</span>) {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">throw</span> <span style="color:#66d9ef">new</span> IllegalStateException(<span style="color:#e6db74">&#34;Payment strategy not set.&#34;</span>);
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>        strategy.<span style="color:#a6e22e">pay</span>(amount);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><h4 id="kotlin-implementation-functional-style-strategy">Kotlin implementation (functional style strategy)</h4>
<p>In kotlin, you can implement Strategy patten using OOP approach and functional style approach. OOP way is similar to how we implemented in java.</p>
<p>Function style strategy</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-kotlin" data-lang="kotlin"><span style="display:flex;"><span><span style="color:#66d9ef">typealias</span> PaymentStrategy = (Double) <span style="color:#f92672">-&gt;</span> Unit
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">PaymentContext</span>(<span style="color:#66d9ef">private</span> <span style="color:#66d9ef">var</span> strategy: PaymentStrategy) {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">fun</span> <span style="color:#a6e22e">setStrategy</span>(strategy: PaymentStrategy) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span>.strategy = strategy
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">fun</span> <span style="color:#a6e22e">pay</span>(amount: Double) = strategy(amount)
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-kotlin" data-lang="kotlin"><span style="display:flex;"><span><span style="color:#66d9ef">fun</span> <span style="color:#a6e22e">main</span>() {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">val</span> creditCardPayment: PaymentStrategy = { amount <span style="color:#f92672">-&gt;</span>
</span></span><span style="display:flex;"><span>        println(<span style="color:#e6db74">&#34;Paid </span><span style="color:#ae81ff">\$</span><span style="color:#e6db74">$amount</span><span style="color:#e6db74"> using Credit Card.&#34;</span>)
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">val</span> paypalPayment: PaymentStrategy = { amount <span style="color:#f92672">-&gt;</span>
</span></span><span style="display:flex;"><span>        println(<span style="color:#e6db74">&#34;Paid </span><span style="color:#ae81ff">\$</span><span style="color:#e6db74">$amount</span><span style="color:#e6db74"> using PayPal.&#34;</span>)
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">val</span> cryptoPayment: PaymentStrategy = { amount <span style="color:#f92672">-&gt;</span>
</span></span><span style="display:flex;"><span>        println(<span style="color:#e6db74">&#34;Paid </span><span style="color:#ae81ff">\$</span><span style="color:#e6db74">$amount</span><span style="color:#e6db74"> using Cryptocurrency.&#34;</span>)
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">val</span> context = PaymentContext(creditCardPayment)
</span></span><span style="display:flex;"><span>    context.setStrategy(paypalPayment)
</span></span><span style="display:flex;"><span>    context.pay(<span style="color:#ae81ff">100.0</span>)
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><h3 id="real-world-use-cases">Real world use-cases</h3>
<ul>
<li>
<p><code>Comparator&lt;T&gt;</code> for sorting in Java</p>
</li>
<li>
<p><code>ThreadPoolExecutor</code> with RejectedExecutionHandler</p>
</li>
<li>
<p>Logging frameworks (ConsoleLogger, FileLogger, RemoteLogger)</p>
</li>
</ul>
<h3 id="drawbacks">Drawbacks</h3>
<ul>
<li>The pattern can lead to explosion of classes and objects. For every new algorithm, you need to create a new concrete strategy class.</li>
<li>The client (or context) needs to be aware of the different available strategies to choose and instantiate the correct one.</li>
<li>While the pattern simplifies the context by removing conditional logic, it can introduce more complexity overall.</li>
<li>For very simple, straightforward algorithms, using a strategy interface and multiple classes can be overkill.</li>
</ul>
<h3 id="parking-lot-problem">Parking Lot Problem</h3>
<p>In this article, let&rsquo;s take it a step further and solve the Parking Lot Problem using the Strategy Pattern.</p>
<p>Problem:
Let&rsquo;s say we want to design a <strong>Parking Lot system</strong>. It should assign an available parking spot to any vehicle that wants to park. The way spots are assigned can vary depending on different rules or criteria (eg: vehicle size, vip vehicle, ..). New requirements might also change how the system chooses a parking spot.</p>
<p>As you can see, there can be multiple ways to assign a parking spot. For example, larger vehicles like trucks may require dedicated spaces that differ from those used by regular cars. Also, we may get new requirements or there may be changes in the requirements.
Using a traditional approach with multiple <code>if-else</code> or <code>switch</code> statements can quickly become hard to manage and scale. A better solution for this scenario is the Strategy Pattern, which allows us to define different spot assignment strategies based on specific criteria, making the system more flexible and maintainable.</p>
<p>Lets first define the strategy</p>
<ol>
<li>Define Strategy</li>
</ol>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#75715e">// implementations will be like Car, Truck, SUV, Bike ..</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">Vehicle</span> {
</span></span><span style="display:flex;"><span>  String <span style="color:#a6e22e">name</span>();
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">ParkingStrategy</span> {
</span></span><span style="display:flex;"><span>  <span style="color:#66d9ef">int</span> <span style="color:#a6e22e">findAvailableSlot</span>(Vehicle vehicle);
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><ol start="2">
<li>Concrete Strategies</li>
</ol>
<p>Lets now define the <code>Concrete Strategies</code>. Let say we have 3 strategies:</p>
<ul>
<li><code>ClosestSpotParkingStrategy</code>: Assign the nearest vacant spot to the entrance to reduce the time taken for vehicles to park.</li>
<li><code>TypeBasedParkingStrategy</code>: Reserve specific spots for different types of vehicles (e.g., compact cars, oversized vehicles).</li>
<li><code>PriorityParkingStrategy</code>: Implement priority parking for certain vehicles based on factors like membership status, VIP status, or special needs.</li>
</ul>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">ClosestSpotParkingStrategy</span> <span style="color:#66d9ef">implements</span> ParkingStrategy {
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">@Override</span>
</span></span><span style="display:flex;"><span>  <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">int</span> <span style="color:#a6e22e">findAvailableSlot</span>(Vehicle vehicle) {
</span></span><span style="display:flex;"><span>    System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(<span style="color:#e6db74">&#34;Using closest spot parking strategy..&#34;</span>);
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// fake spot number</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> 17; <span style="color:#75715e">// implement closest spot parking logic</span>
</span></span><span style="display:flex;"><span>  }
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">TypeBasedParkingStrategy</span> <span style="color:#66d9ef">implements</span> ParkingStrategy {
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">@Override</span>
</span></span><span style="display:flex;"><span>  <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">int</span> <span style="color:#a6e22e">findAvailableSlot</span>(Vehicle vehicle) {
</span></span><span style="display:flex;"><span>    System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(<span style="color:#e6db74">&#34;Using type based parking strategy..&#34;</span>);
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// fake spot number</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> 101; <span style="color:#75715e">// implement type based spot parking logic</span>
</span></span><span style="display:flex;"><span>  }
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">PriorityParkingStrategy</span> <span style="color:#66d9ef">implements</span> ParkingStrategy {
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">@Override</span>
</span></span><span style="display:flex;"><span>  <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">int</span> <span style="color:#a6e22e">findAvailableSlot</span>(Vehicle vehicle) {
</span></span><span style="display:flex;"><span>    System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(<span style="color:#e6db74">&#34;Using priority parking strategy..&#34;</span>);
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// fake spot number</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> 1011; <span style="color:#75715e">// implement priority spot parking logic</span>
</span></span><span style="display:flex;"><span>  }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>As you can see, we can easily create new strategies by implementing the <code>ParkingStategy</code> interface and implement the logic based on new requirements without modifying the existing code.</p>
<ol start="3">
<li>Define Context Class</li>
</ol>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">ParkingLot</span> {
</span></span><span style="display:flex;"><span>  <span style="color:#75715e">// default strategy</span>
</span></span><span style="display:flex;"><span>  <span style="color:#66d9ef">private</span> ParkingStrategy strategy <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> ClosestSpotParkingStrategy();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>  <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">ParkingLot</span>() {}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>  <span style="color:#75715e">// or provide default strategy</span>
</span></span><span style="display:flex;"><span>  <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">ParkingLot</span>(ParkingStrategy strategy) {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">strategy</span> <span style="color:#f92672">=</span> strategy;
</span></span><span style="display:flex;"><span>  }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>  <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">setParkingStrategy</span>(ParkingStrategy strategy) {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">strategy</span> <span style="color:#f92672">=</span> strategy;
</span></span><span style="display:flex;"><span>  }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>  <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">int</span> <span style="color:#a6e22e">parkVehicle</span>(Vehicle vehicle) {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">int</span> slot <span style="color:#f92672">=</span> strategy.<span style="color:#a6e22e">findAvailableSlot</span>(vehicle);
</span></span><span style="display:flex;"><span>    System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(<span style="color:#e6db74">&#34;Parking &#34;</span> <span style="color:#f92672">+</span> vehicle.<span style="color:#a6e22e">name</span>() <span style="color:#f92672">+</span> <span style="color:#e6db74">&#34; in slot -&gt; &#34;</span> <span style="color:#f92672">+</span> slot <span style="color:#f92672">+</span> <span style="color:#e6db74">&#34;.&#34;</span>);
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> slot;
</span></span><span style="display:flex;"><span>  }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><ol start="4">
<li>Client code implementation</li>
</ol>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Application</span> {
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>  <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">main</span>(String<span style="color:#f92672">[]</span> args) {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">final</span> <span style="color:#66d9ef">var</span> parkingLot <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> ParkingLot();
</span></span><span style="display:flex;"><span>    parkingLot.<span style="color:#a6e22e">setParkingStrategy</span>(<span style="color:#66d9ef">new</span> PriorityParkingStrategy());
</span></span><span style="display:flex;"><span>    parkingLot.<span style="color:#a6e22e">parkVehicle</span>(<span style="color:#66d9ef">new</span> Car(<span style="color:#e6db74">&#34;Rolls-Royce&#34;</span>));
</span></span><span style="display:flex;"><span>  }
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#960050;background-color:#1e0010">###</span> Conclusion
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>The Strategy Pattern is a powerful behavioral design pattern that promotes flexibility and maintainability in your code. By encapsulating algorithms into separate <span style="color:#a6e22e">classes</span> (strategies), it allows you to <span style="color:#66d9ef">switch</span> between them at runtime, eliminating the need <span style="color:#66d9ef">for</span> complex conditional statements.
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>While Strategy Pattern introduces more classes, the benefits of decoupling the algorithm from the context often outweigh <span style="color:#66d9ef">this</span> drawback, especially in complex applications where behavior needs to change dynamically.
</span></span></code></pre></div>]]></content>
        </item>
        
        <item>
            <title>Builder Design Pattern</title>
            <link>https://aamernabi.github.io/posts/builder-design-pattern/</link>
            <pubDate>Mon, 28 Jul 2025 18:30:20 +0530</pubDate>
            
            <guid>https://aamernabi.github.io/posts/builder-design-pattern/</guid>
            <description>&lt;p&gt;The &lt;strong&gt;Builder Design Pattern&lt;/strong&gt; is a creational design pattern that lets you construct complex objects step by step. Using Builder pattern you can use same construction process to can create different representations.&lt;/p&gt;
&lt;h3 id=&#34;use-case&#34;&gt;Use case&lt;/h3&gt;
&lt;p&gt;Use the Builder Pattern when:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;An object has many &lt;strong&gt;optional fields or configurations&lt;/strong&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;You want to avoid constructor telescoping (i.e., too many overloaded constructors).&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;You need to create &lt;strong&gt;immutable objects&lt;/strong&gt; step by step.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;&#34;&gt;&lt;code class=&#34;language-java&#34; data-lang=&#34;java&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;public&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;class&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;User&lt;/span&gt; {
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;private&lt;/span&gt; String firstName;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;private&lt;/span&gt; String lastName;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;private&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;int&lt;/span&gt; age;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;private&lt;/span&gt; String email;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;private&lt;/span&gt; String phone;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;public&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;User&lt;/span&gt;(String firstName, String lastName) { ... }
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;public&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;User&lt;/span&gt;(String firstName, String lastName, &lt;span style=&#34;color:#66d9ef&#34;&gt;int&lt;/span&gt; age) { ... }
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;public&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;User&lt;/span&gt;(String firstName, String lastName, &lt;span style=&#34;color:#66d9ef&#34;&gt;int&lt;/span&gt; age, String email) { ... }
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#75715e&#34;&gt;// ...&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;}
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;In above example, you can see &lt;code&gt;User&lt;/code&gt; class is hard to maintain and read.&lt;/p&gt;</description>
            <content type="html"><![CDATA[<p>The <strong>Builder Design Pattern</strong> is a creational design pattern that lets you construct complex objects step by step. Using Builder pattern you can use same construction process to can create different representations.</p>
<h3 id="use-case">Use case</h3>
<p>Use the Builder Pattern when:</p>
<ul>
<li>
<p>An object has many <strong>optional fields or configurations</strong>.</p>
</li>
<li>
<p>You want to avoid constructor telescoping (i.e., too many overloaded constructors).</p>
</li>
<li>
<p>You need to create <strong>immutable objects</strong> step by step.</p>
</li>
</ul>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">User</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> String firstName;
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> String lastName;
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">int</span> age;
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> String email;
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> String phone;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">User</span>(String firstName, String lastName) { ... }
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">User</span>(String firstName, String lastName, <span style="color:#66d9ef">int</span> age) { ... }
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">User</span>(String firstName, String lastName, <span style="color:#66d9ef">int</span> age, String email) { ... }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// ...</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>In above example, you can see <code>User</code> class is hard to maintain and read.</p>
<h3 id="core-concepts">Core Concepts</h3>
<ol>
<li><strong>Product</strong>: The complex object being built. It&rsquo;s typically a class with many fields.</li>
<li><strong>Builder</strong>: An interface or abstract class that defines the steps to build the product.</li>
<li><strong>ConcreteBuilder</strong>: A class that implements the Builder interface and provides specific implementation for building the product. It keeps track of the object being built and provides a method (<code>build</code>) to return the final product.</li>
</ol>
<p>Note: The Builder pattern can be implemented with or without a formal Builder interface or abstract class. The core concept is the separate builder object, not the strict use of an interface.</p>
<h3 id="implementation">Implementation</h3>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">User</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Required fields </span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">final</span> String firstName;
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">final</span> String lastName;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Optional fields</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">final</span> Integer age;
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">final</span> String email;
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">final</span> String phone;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#a6e22e">User</span>(Builder builder) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">firstName</span> <span style="color:#f92672">=</span> builder.<span style="color:#a6e22e">firstName</span>;
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">lastName</span> <span style="color:#f92672">=</span> builder.<span style="color:#a6e22e">lastName</span>;
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">age</span> <span style="color:#f92672">=</span> builder.<span style="color:#a6e22e">age</span>;
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">email</span> <span style="color:#f92672">=</span> builder.<span style="color:#a6e22e">email</span>;
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">phone</span> <span style="color:#f92672">=</span> builder.<span style="color:#a6e22e">phone</span>;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Builder Class</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Builder</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">final</span> String firstName;
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">final</span> String lastName;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">private</span> Integer age;
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">private</span> String email;
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">private</span> String phone;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">Builder</span>(String firstName, String lastName) {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">firstName</span> <span style="color:#f92672">=</span> firstName;
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">lastName</span> <span style="color:#f92672">=</span> lastName;
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">public</span> Builder <span style="color:#a6e22e">age</span>(<span style="color:#66d9ef">int</span> age) {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">age</span> <span style="color:#f92672">=</span> age;
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">this</span>;
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">public</span> Builder <span style="color:#a6e22e">email</span>(String email) {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">email</span> <span style="color:#f92672">=</span> email;
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">this</span>;
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">public</span> Builder <span style="color:#a6e22e">phone</span>(String phone) {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">phone</span> <span style="color:#f92672">=</span> phone;
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">this</span>;
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">public</span> User <span style="color:#a6e22e">build</span>() {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">new</span> User(<span style="color:#66d9ef">this</span>);
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">@Override</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> String <span style="color:#a6e22e">toString</span>() {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#e6db74">&#34;User{&#34;</span> <span style="color:#f92672">+</span>
</span></span><span style="display:flex;"><span>                <span style="color:#e6db74">&#34;firstName=&#39;&#34;</span> <span style="color:#f92672">+</span> firstName <span style="color:#f92672">+</span> <span style="color:#e6db74">&#39;\&#39;&#39;</span> <span style="color:#f92672">+</span>
</span></span><span style="display:flex;"><span>                <span style="color:#e6db74">&#34;, lastName=&#39;&#34;</span> <span style="color:#f92672">+</span> lastName <span style="color:#f92672">+</span> <span style="color:#e6db74">&#39;\&#39;&#39;</span> <span style="color:#f92672">+</span>
</span></span><span style="display:flex;"><span>                <span style="color:#e6db74">&#34;, age=&#34;</span> <span style="color:#f92672">+</span> age <span style="color:#f92672">+</span>
</span></span><span style="display:flex;"><span>                <span style="color:#e6db74">&#34;, email=&#39;&#34;</span> <span style="color:#f92672">+</span> email <span style="color:#f92672">+</span> <span style="color:#e6db74">&#39;\&#39;&#39;</span> <span style="color:#f92672">+</span>
</span></span><span style="display:flex;"><span>                <span style="color:#e6db74">&#34;, phone=&#39;&#34;</span> <span style="color:#f92672">+</span> phone <span style="color:#f92672">+</span> <span style="color:#e6db74">&#39;\&#39;&#39;</span> <span style="color:#f92672">+</span>
</span></span><span style="display:flex;"><span>                <span style="color:#e6db74">&#39;}&#39;</span>;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Client Code:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Main</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">main</span>(String<span style="color:#f92672">[]</span> args) {
</span></span><span style="display:flex;"><span>        User user <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> User.<span style="color:#a6e22e">Builder</span>(<span style="color:#e6db74">&#34;John&#34;</span>, <span style="color:#e6db74">&#34;Doe&#34;</span>)
</span></span><span style="display:flex;"><span>                .<span style="color:#a6e22e">age</span>(30)
</span></span><span style="display:flex;"><span>                .<span style="color:#a6e22e">email</span>(<span style="color:#e6db74">&#34;john@example.com&#34;</span>)
</span></span><span style="display:flex;"><span>                .<span style="color:#a6e22e">phone</span>(<span style="color:#e6db74">&#34;1234567890&#34;</span>)
</span></span><span style="display:flex;"><span>                .<span style="color:#a6e22e">build</span>();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(user);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><h3 id="real-world-examples">Real world examples</h3>
<ul>
<li>StringBuilder (JDK)</li>
<li>java.time.LocalDateTime.Builder</li>
<li>AlertDialog.Builder in Android</li>
<li>Libraries like Lombok, Project Lombok @Builder</li>
</ul>
<h3 id="drawbacks">Drawbacks</h3>
<ul>
<li>More boilerplate code</li>
<li>Verbose</li>
<li>Testing complexity</li>
<li>Cannot enforce field dependencies easily</li>
</ul>
<h3 id="kotlin-implementation-using-dsl">Kotlin Implementation (using DSL)</h3>
<p>You can simplify builder creation using Kotlin&rsquo;s function literals with <strong>receivers</strong>:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-kotlin" data-lang="kotlin"><span style="display:flex;"><span><span style="color:#66d9ef">data</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">User</span>(
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">val</span> firstName: String,
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">val</span> lastName: String,
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> age: Int? = <span style="color:#66d9ef">null</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> email: String? = <span style="color:#66d9ef">null</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> phone: String? = <span style="color:#66d9ef">null</span>
</span></span><span style="display:flex;"><span>)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">UserBuilder</span>(<span style="color:#66d9ef">private</span> <span style="color:#66d9ef">val</span> firstName: String, <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">val</span> lastName: String) {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> age: Int? = <span style="color:#66d9ef">null</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> email: String? = <span style="color:#66d9ef">null</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> phone: String? = <span style="color:#66d9ef">null</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">fun</span> <span style="color:#a6e22e">build</span>() = User(firstName, lastName, age, email, phone)
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">fun</span> <span style="color:#a6e22e">buildUser</span>(firstName: String, lastName: String, block: <span style="color:#a6e22e">UserBuilder</span>.() <span style="color:#f92672">-&gt;</span> Unit): User {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">val</span> builder = UserBuilder(firstName, lastName)
</span></span><span style="display:flex;"><span>    builder.block()
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> builder.build()
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Client Code</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-kotlin" data-lang="kotlin"><span style="display:flex;"><span><span style="color:#66d9ef">val</span> user = buildUser(<span style="color:#e6db74">&#34;Jane&#34;</span>, <span style="color:#e6db74">&#34;Doe&#34;</span>) {
</span></span><span style="display:flex;"><span>    age = <span style="color:#ae81ff">28</span>
</span></span><span style="display:flex;"><span>    email = <span style="color:#e6db74">&#34;jane@example.com&#34;</span>
</span></span><span style="display:flex;"><span>    phone = <span style="color:#e6db74">&#34;012356789&#34;</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div>]]></content>
        </item>
        
        <item>
            <title>Factory and Abstract Factory Design Pattern</title>
            <link>https://aamernabi.github.io/posts/factory-design-pattern/</link>
            <pubDate>Sun, 27 Jul 2025 10:51:59 +0530</pubDate>
            
            <guid>https://aamernabi.github.io/posts/factory-design-pattern/</guid>
            <description>&lt;h2 id=&#34;factory-design-pattern&#34;&gt;Factory Design Pattern&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Factory Pattern&lt;/strong&gt; is &lt;strong&gt;creational pattern&lt;/strong&gt; that delegate the instantiation of objects to a &lt;strong&gt;separate method or class&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;The Factory design pattern provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that&amp;rsquo;ll be created. This pattern helps to decouple the client code from the concrete classes it needs to instantiate.&lt;/p&gt;
&lt;h3 id=&#34;core-components&#34;&gt;Core Components&lt;/h3&gt;
&lt;p&gt;The Factory pattern has three main components:&lt;/p&gt;</description>
            <content type="html"><![CDATA[<h2 id="factory-design-pattern">Factory Design Pattern</h2>
<p><strong>Factory Pattern</strong> is <strong>creational pattern</strong> that delegate the instantiation of objects to a <strong>separate method or class</strong>.</p>
<p>The Factory design pattern provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that&rsquo;ll be created. This pattern helps to decouple the client code from the concrete classes it needs to instantiate.</p>
<h3 id="core-components">Core Components</h3>
<p>The Factory pattern has three main components:</p>
<ol>
<li>
<p><strong>Product</strong>: This is the interface that all objects created by the factory must implement.</p>
</li>
<li>
<p><strong>Concrete Products</strong>: These are the actual implementations of the Product interface. The factory will create these objects.</p>
</li>
<li>
<p><strong>Creator (Factory)</strong> : This class declares the method that returns a Product object.</p>
</li>
</ol>
<h3 id="use-cases">Use cases</h3>
<ul>
<li>When you need to create objects without exposing instantiation logic</li>
<li>When your code needs to work with multiple related classes</li>
<li>When object creation involves complex logic</li>
</ul>
<h3 id="example">Example</h3>
<ol>
<li>Create an Interface (Product)</li>
</ol>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">Shape</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">draw</span>();
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><ol start="2">
<li>Concrete Implementations (Concrete Products)</li>
</ol>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Circle</span> <span style="color:#66d9ef">implements</span> Shape {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">draw</span>() {
</span></span><span style="display:flex;"><span>        System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(<span style="color:#e6db74">&#34;Drawing a Circle&#34;</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Rectangle</span> <span style="color:#66d9ef">implements</span> Shape {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">draw</span>() {
</span></span><span style="display:flex;"><span>        System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(<span style="color:#e6db74">&#34;Drawing a Rectangle&#34;</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Square</span> <span style="color:#66d9ef">implements</span> Shape {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">draw</span>() {
</span></span><span style="display:flex;"><span>        System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(<span style="color:#e6db74">&#34;Drawing a Square&#34;</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><ol start="3">
<li>Factory Class (Creator)</li>
</ol>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">ShapeFactory</span> {
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Factory method</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> Shape <span style="color:#a6e22e">getShape</span>(String shapeType) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (shapeType <span style="color:#f92672">==</span> <span style="color:#66d9ef">null</span>) {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">null</span>;
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">switch</span> (shapeType.<span style="color:#a6e22e">toLowerCase</span>()) {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">case</span> <span style="color:#e6db74">&#34;circle&#34;</span>:
</span></span><span style="display:flex;"><span>                <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">new</span> Circle();
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">case</span> <span style="color:#e6db74">&#34;rectangle&#34;</span>:
</span></span><span style="display:flex;"><span>                <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">new</span> Rectangle();
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">case</span> <span style="color:#e6db74">&#34;square&#34;</span>:
</span></span><span style="display:flex;"><span>                <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">new</span> Square();
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">default</span>:
</span></span><span style="display:flex;"><span>                <span style="color:#66d9ef">throw</span> <span style="color:#66d9ef">new</span> IllegalArgumentException(<span style="color:#e6db74">&#34;Unknown shape type: &#34;</span> <span style="color:#f92672">+</span> shapeType);
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><ol start="4">
<li>Client Code</li>
</ol>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Main</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">main</span>(String<span style="color:#f92672">[]</span> args) {
</span></span><span style="display:flex;"><span>        ShapeFactory factory <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> ShapeFactory();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        Shape shape1 <span style="color:#f92672">=</span> factory.<span style="color:#a6e22e">getShape</span>(<span style="color:#e6db74">&#34;circle&#34;</span>);
</span></span><span style="display:flex;"><span>        shape1.<span style="color:#a6e22e">draw</span>();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        Shape shape2 <span style="color:#f92672">=</span> factory.<span style="color:#a6e22e">getShape</span>(<span style="color:#e6db74">&#34;rectangle&#34;</span>);
</span></span><span style="display:flex;"><span>        shape2.<span style="color:#a6e22e">draw</span>();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        Shape shape3 <span style="color:#f92672">=</span> factory.<span style="color:#a6e22e">getShape</span>(<span style="color:#e6db74">&#34;square&#34;</span>);
</span></span><span style="display:flex;"><span>        shape3.<span style="color:#a6e22e">draw</span>();
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><h4 id="kotlin-implementation">Kotlin Implementation</h4>
<p>Using sealed classes improves type safety and ensures all cases are handled at compile time.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-kotlin" data-lang="kotlin"><span style="display:flex;"><span><span style="color:#66d9ef">sealed</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">ShapeType</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">object</span> <span style="color:#a6e22e">Circle</span> : ShapeType()
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">object</span> <span style="color:#a6e22e">Square</span> : ShapeType()
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">object</span> <span style="color:#a6e22e">Rectangle</span> : ShapeType()
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">Shape</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">fun</span> <span style="color:#a6e22e">draw</span>()
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Creator (Factory Method)
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#66d9ef">companion</span> <span style="color:#66d9ef">object</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">fun</span> <span style="color:#a6e22e">create</span>(type: ShapeType): Shape = <span style="color:#66d9ef">when</span> (type) {
</span></span><span style="display:flex;"><span>            <span style="color:#a6e22e">ShapeType</span>.Circle <span style="color:#f92672">-&gt;</span> Circle()
</span></span><span style="display:flex;"><span>            <span style="color:#a6e22e">ShapeType</span>.Square <span style="color:#f92672">-&gt;</span> Square()
</span></span><span style="display:flex;"><span>            <span style="color:#a6e22e">ShapeType</span>.Rectangle <span style="color:#f92672">-&gt;</span> Rectangle()
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// concrete creators
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Circle</span> : Shape {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">override</span> <span style="color:#66d9ef">fun</span> <span style="color:#a6e22e">draw</span>() = println(<span style="color:#e6db74">&#34;Drawing a Circle&#34;</span>)
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Square</span> : Shape {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">override</span> <span style="color:#66d9ef">fun</span> <span style="color:#a6e22e">draw</span>() = println(<span style="color:#e6db74">&#34;Drawing a Square&#34;</span>)
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Rectangle</span> : Shape {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">override</span> <span style="color:#66d9ef">fun</span> <span style="color:#a6e22e">draw</span>() = println(<span style="color:#e6db74">&#34;Drawing a Rectangle&#34;</span>)
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// client code
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">fun</span> <span style="color:#a6e22e">main</span>() {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">val</span> shape = <span style="color:#a6e22e">Shape</span>.create(<span style="color:#a6e22e">ShapeType</span>.Rectangle)
</span></span><span style="display:flex;"><span>    shape.draw()
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><h3 id="drawbacks">Drawbacks</h3>
<ul>
<li>Code can become bloated with many conditionals</li>
<li>Not ideal for few object types</li>
</ul>
<p>We can use Abstract Factory Pattern to fix code bloat.</p>
<h2 id="abstract-factory-design-pattern">Abstract Factory Design Pattern</h2>
<p>The Abstract Factory Pattern is an extension of the Factory Method Pattern. Abstract Factory provides an interface for creating <strong>families of related</strong> or <strong>dependent objects</strong> without specifying their concrete classes.</p>
<h3 id="core-components-1">Core Components</h3>
<p>The Abstract Factory pattern consists of four main roles:</p>
<ol>
<li>
<p><strong>Abstract Product</strong>: These are the interfaces for each type of product in the family (e.g., <code>Button</code>, <code>Checkbox</code>).</p>
</li>
<li>
<p><strong>Concrete Product</strong>: These are the actual implementations of the Abstract Products, grouped by their specific variant (e.g., <code>AndroidButton</code>, <code>iOSButton</code>).</p>
</li>
<li>
<p><strong>Abstract Factory</strong>: This is an interface that declares the creation methods for each distinct product in the product family.</p>
</li>
<li>
<p><strong>Concrete Factory</strong>: These classes implement the Abstract Factory interface, with each one corresponding to a specific variant or family of products. They are responsible for creating the concrete products.</p>
</li>
</ol>
<h3 id="example-1">Example</h3>
<ol>
<li>Product Interfaces</li>
</ol>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">Button</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">click</span>();
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">Checkbox</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">check</span>();
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><ol start="2">
<li>Concrete Products</li>
</ol>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">AndroidButton</span> <span style="color:#66d9ef">implements</span> Button {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">click</span>() {
</span></span><span style="display:flex;"><span>        System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(<span style="color:#e6db74">&#34;Android Button Clicked&#34;</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">AndroidCheckbox</span> <span style="color:#66d9ef">implements</span> Checkbox {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">check</span>() {
</span></span><span style="display:flex;"><span>        System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(<span style="color:#e6db74">&#34;Android Checkbox Checked&#34;</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">IOSButton</span> <span style="color:#66d9ef">implements</span> Button {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">click</span>() {
</span></span><span style="display:flex;"><span>        System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(<span style="color:#e6db74">&#34;iOS Button Clicked&#34;</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">IOSCheckbox</span> <span style="color:#66d9ef">implements</span> Checkbox {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">check</span>() {
</span></span><span style="display:flex;"><span>        System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(<span style="color:#e6db74">&#34;iOS Checkbox Checked&#34;</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><ol start="3">
<li>Abstract Factory Interface</li>
</ol>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">UIFactory</span> {
</span></span><span style="display:flex;"><span>    Button <span style="color:#a6e22e">createButton</span>();
</span></span><span style="display:flex;"><span>    Checkbox <span style="color:#a6e22e">createCheckbox</span>();
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><ol start="4">
<li>Concrete Factories</li>
</ol>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">AndroidUiFactory</span> <span style="color:#66d9ef">implements</span> UIFactory {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">@Override</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> Button <span style="color:#a6e22e">createButton</span>() {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">new</span> AndroidButton();
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">@Override</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> Checkbox <span style="color:#a6e22e">createCheckbox</span>() {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">new</span> AndroidCheckbox();
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">IOSUiFactory</span> <span style="color:#66d9ef">implements</span> UIFactory {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">@Override</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> Button <span style="color:#a6e22e">createButton</span>() {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">new</span> IOSButton();
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">@Override</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> Checkbox <span style="color:#a6e22e">createCheckbox</span>() {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">new</span> IOSCheckbox();
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><ol start="5">
<li>Client Code</li>
</ol>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Application</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> Button button;
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> Checkbox checkbox;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">Application</span>(UIFactory factory) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">button</span> <span style="color:#f92672">=</span> factory.<span style="color:#a6e22e">createButton</span>();
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">checkbox</span> <span style="color:#f92672">=</span> factory.<span style="color:#a6e22e">createCheckbox</span>();
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">render</span>() {
</span></span><span style="display:flex;"><span>        button.<span style="color:#a6e22e">click</span>();
</span></span><span style="display:flex;"><span>        checkbox.<span style="color:#a6e22e">check</span>();
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">main</span>(String<span style="color:#f92672">[]</span> args) {
</span></span><span style="display:flex;"><span>        UIFactory factory;
</span></span><span style="display:flex;"><span>        String osName <span style="color:#f92672">=</span> <span style="color:#e6db74">&#34;iOS&#34;</span>; <span style="color:#75715e">// This could be determined at runtime, like Platform.getName();</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (osName.<span style="color:#a6e22e">toLowerCase</span>().<span style="color:#a6e22e">contains</span>(<span style="color:#e6db74">&#34;iOS&#34;</span>, <span style="color:#66d9ef">true</span>)) {
</span></span><span style="display:flex;"><span>            factory <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> IOSUiFactory();
</span></span><span style="display:flex;"><span>        } <span style="color:#66d9ef">else</span> {
</span></span><span style="display:flex;"><span>            factory <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> AndroidUiFactory();
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        Application app <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> Application(factory);
</span></span><span style="display:flex;"><span>        app.<span style="color:#a6e22e">render</span>();
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><h4 id="kotlin-implementation-1">Kotlin Implementation</h4>
<p>Instead of creating new factory instances, we can use use <code>object</code> for singleton-like factories.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-kotlin" data-lang="kotlin"><span style="display:flex;"><span><span style="color:#75715e">// Product Interfaces
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// We use a sealed interface to restrict the possible implementations of Button and Checkbox
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// This allows for exhaustive &#39;when&#39; expressions in consuming code.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">sealed</span> <span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">Button</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">fun</span> <span style="color:#a6e22e">click</span>()
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">sealed</span> <span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">Checkbox</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">fun</span> <span style="color:#a6e22e">check</span>()
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Concrete Products
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">AndroidButton</span> : Button {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">override</span> <span style="color:#66d9ef">fun</span> <span style="color:#a6e22e">click</span>() {
</span></span><span style="display:flex;"><span>        println(<span style="color:#e6db74">&#34;Android Button Clicked&#34;</span>)
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">AndroidCheckbox</span> : Checkbox {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">override</span> <span style="color:#66d9ef">fun</span> <span style="color:#a6e22e">check</span>() {
</span></span><span style="display:flex;"><span>        println(<span style="color:#e6db74">&#34;Android Checkbox Checked&#34;</span>)
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">IOSButton</span> : Button {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">override</span> <span style="color:#66d9ef">fun</span> <span style="color:#a6e22e">click</span>() {
</span></span><span style="display:flex;"><span>        println(<span style="color:#e6db74">&#34;iOS Button Clicked&#34;</span>)
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">IOSCheckbox</span> : Checkbox {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">override</span> <span style="color:#66d9ef">fun</span> <span style="color:#a6e22e">check</span>() {
</span></span><span style="display:flex;"><span>        println(<span style="color:#e6db74">&#34;iOS Checkbox Checked&#34;</span>)
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Abstract Factory Interface
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">sealed</span> <span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">UIFactory</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">fun</span> <span style="color:#a6e22e">createButton</span>(): Button
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">fun</span> <span style="color:#a6e22e">createCheckbox</span>(): Checkbox
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Concrete Factories
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// We use &#39;object&#39; declarations for stateless, singleton factories.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// This is more concise and thread-safe than a class with a companion object.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">object</span> <span style="color:#a6e22e">AndroidUiFactory</span> : UIFactory {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">override</span> <span style="color:#66d9ef">fun</span> <span style="color:#a6e22e">createButton</span>(): Button = AndroidButton()
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">override</span> <span style="color:#66d9ef">fun</span> <span style="color:#a6e22e">createCheckbox</span>(): Checkbox = AndroidCheckbox()
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">object</span> <span style="color:#a6e22e">IOSUiFactory</span> : UIFactory {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">override</span> <span style="color:#66d9ef">fun</span> <span style="color:#a6e22e">createButton</span>(): Button = IOSButton()
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">override</span> <span style="color:#66d9ef">fun</span> <span style="color:#a6e22e">createCheckbox</span>(): Checkbox = IOSCheckbox()
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Client Code
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// Remains similar to the Java version.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Application</span>(<span style="color:#66d9ef">private</span> <span style="color:#66d9ef">val</span> factory: UIFactory) {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">val</span> button: Button = factory.createButton()
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">val</span> checkbox: Checkbox = factory.createCheckbox()
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">fun</span> <span style="color:#a6e22e">render</span>() {
</span></span><span style="display:flex;"><span>        button.click()
</span></span><span style="display:flex;"><span>        checkbox.check()
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">fun</span> <span style="color:#a6e22e">main</span>() {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">val</span> osName = <span style="color:#e6db74">&#34;iOS&#34;</span> <span style="color:#75715e">// This would be determined dynamically in a real app
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">val</span> factory: UIFactory = <span style="color:#66d9ef">when</span> (osName.lowercase()) {
</span></span><span style="display:flex;"><span>        <span style="color:#e6db74">&#34;ios&#34;</span> <span style="color:#f92672">-&gt;</span> IOSUiFactory
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">else</span> <span style="color:#f92672">-&gt;</span> AndroidUiFactory
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">val</span> app = Application(factory)
</span></span><span style="display:flex;"><span>    app.render()
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><h3 id="abstract-factory-vs-factory-method">Abstract Factory vs Factory Method</h3>
<table>
  <thead>
      <tr>
          <th><strong>Feature</strong></th>
          <th><strong>Abstract Factory</strong></th>
          <th><strong>Factory Method</strong></th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td><strong>Purpose</strong></td>
          <td>Creates entire families of related objects.</td>
          <td>Creates a single object.</td>
      </tr>
      <tr>
          <td><strong>Structure</strong></td>
          <td>A &ldquo;factory of factories&rdquo; where a factory class creates multiple types of products.</td>
          <td>A single factory method in a superclass that subclasses override to create objects.</td>
      </tr>
      <tr>
          <td><strong>Complexity</strong></td>
          <td>More complex, as it involves multiple interfaces and classes.</td>
          <td>Simpler, often implemented with just a few classes.</td>
      </tr>
  </tbody>
</table>
]]></content>
        </item>
        
        <item>
            <title>Singleton Design Pattern</title>
            <link>https://aamernabi.github.io/posts/singleton-design-pattern/</link>
            <pubDate>Sat, 26 Jul 2025 11:02:04 +0530</pubDate>
            
            <guid>https://aamernabi.github.io/posts/singleton-design-pattern/</guid>
            <description>&lt;p&gt;&lt;strong&gt;Singleton design pattern&lt;/strong&gt; is a creational design pattern that restricts instantiation of a class ensuring class has only &lt;strong&gt;one instance&lt;/strong&gt; and provide a &lt;strong&gt;global point&lt;/strong&gt; of access to it.&lt;/p&gt;
&lt;h3 id=&#34;common-implementations&#34;&gt;Common Implementations&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Lazy Initialization&lt;/strong&gt;: ensures instance is created only when it is first requested.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Eager Initialization&lt;/strong&gt;: instance is created when the class is loaded.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Thread-Safe Implementations&lt;/strong&gt;: ensures the singleton works correctly in multi-threaded environments, such as using &lt;code&gt;synchronized&lt;/code&gt; methods or double-checked locking.
(though double-checked locking has nuances and is sometimes considered an anti-pattern in modern Java)&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&#34;use-cases&#34;&gt;Use Cases&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Logging&lt;/li&gt;
&lt;li&gt;Configuration settings&lt;/li&gt;
&lt;li&gt;Thread pools&lt;/li&gt;
&lt;li&gt;Caches&lt;/li&gt;
&lt;li&gt;Device drivers&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&#34;examples&#34;&gt;Examples&lt;/h3&gt;
&lt;h4 id=&#34;eager-initialization&#34;&gt;Eager initialization&lt;/h4&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;&#34;&gt;&lt;code class=&#34;language-java&#34; data-lang=&#34;java&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;public&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;class&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;Singleton&lt;/span&gt; {
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;private&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;static&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;final&lt;/span&gt; Singleton instance &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;new&lt;/span&gt; Singleton();
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;private&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;EagerInitializedSingleton&lt;/span&gt;(){}
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;public&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;static&lt;/span&gt; Singleton &lt;span style=&#34;color:#a6e22e&#34;&gt;getInstance&lt;/span&gt;() {
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; instance;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    }
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;}
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;ul&gt;
&lt;li&gt;Useful if your singleton class is not using a lot of resources.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&#34;using-synchronized-method-lazy-initialization&#34;&gt;Using &lt;code&gt;synchronized&lt;/code&gt; method (Lazy initialization)&lt;/h4&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;&#34;&gt;&lt;code class=&#34;language-java&#34; data-lang=&#34;java&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;public&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;class&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;Singleton&lt;/span&gt; {
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#75715e&#34;&gt;// Volatile ensures visibility and prevents reordering&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;private&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;static&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;volatile&lt;/span&gt; Singleton instance;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;private&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;Singleton&lt;/span&gt;() {
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    }
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#75715e&#34;&gt;// Thread-safe with method-level synchronization&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;public&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;static&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;synchronized&lt;/span&gt; Singleton &lt;span style=&#34;color:#a6e22e&#34;&gt;getInstance&lt;/span&gt;() {
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        &lt;span style=&#34;color:#66d9ef&#34;&gt;if&lt;/span&gt; (instance &lt;span style=&#34;color:#f92672&#34;&gt;==&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;null&lt;/span&gt;) {
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;            instance &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;new&lt;/span&gt; Singleton();
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        }
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; instance;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    }
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;public&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;void&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;example&lt;/span&gt;() {
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        System.&lt;span style=&#34;color:#a6e22e&#34;&gt;out&lt;/span&gt;.&lt;span style=&#34;color:#a6e22e&#34;&gt;println&lt;/span&gt;(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;Hello from Singleton!, (using synchronized method)&amp;#34;&lt;/span&gt;);
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    }
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;}
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;ul&gt;
&lt;li&gt;Lazily initialization the instance.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;synchronized&lt;/code&gt; ensures that only one thread can enter the method at a time.&lt;/li&gt;
&lt;li&gt;It ensures lazy initialization — Singleton instance is created only when needed.&lt;/li&gt;
&lt;li&gt;Performance overhead: Every call to &lt;code&gt;getInstance()&lt;/code&gt; acquires a lock, even after the instance has been initialized. This is unnecessary and can be expensive under heavy load.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&#34;double-checked-locking-lazy-initialization&#34;&gt;Double-Checked Locking (Lazy initialization)&lt;/h4&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;&#34;&gt;&lt;code class=&#34;language-java&#34; data-lang=&#34;java&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;public&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;class&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;Singleton&lt;/span&gt; {
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;private&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;static&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;volatile&lt;/span&gt; Singleton instance;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;private&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;Singleton&lt;/span&gt;() {}
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;public&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;static&lt;/span&gt; Singleton &lt;span style=&#34;color:#a6e22e&#34;&gt;getInstance&lt;/span&gt;() {
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        &lt;span style=&#34;color:#66d9ef&#34;&gt;if&lt;/span&gt; (instance &lt;span style=&#34;color:#f92672&#34;&gt;==&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;null&lt;/span&gt;) {
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;            &lt;span style=&#34;color:#66d9ef&#34;&gt;synchronized&lt;/span&gt; (Singleton.&lt;span style=&#34;color:#a6e22e&#34;&gt;class&lt;/span&gt;) {
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                &lt;span style=&#34;color:#66d9ef&#34;&gt;if&lt;/span&gt; (instance &lt;span style=&#34;color:#f92672&#34;&gt;==&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;null&lt;/span&gt;) { &lt;span style=&#34;color:#75715e&#34;&gt;// &amp;lt;- Double-check&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                    instance &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;new&lt;/span&gt; Singleton();
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                }
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;            }
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        }
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; instance;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    }
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;public&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;void&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;example&lt;/span&gt;() {
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        System.&lt;span style=&#34;color:#a6e22e&#34;&gt;out&lt;/span&gt;.&lt;span style=&#34;color:#a6e22e&#34;&gt;println&lt;/span&gt;(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;Hello from Singleton!, (double-check)&amp;#34;&lt;/span&gt;);
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    }
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;}
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;ul&gt;
&lt;li&gt;Lazily initialization the instance.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;double check&lt;/strong&gt; aims to minimize the overhead of synchronization.&lt;/li&gt;
&lt;li&gt;Complex&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&#34;bill-pugh-inner-class---recommended-approach&#34;&gt;Bill Pugh (Inner Class) - Recommended Approach&lt;/h4&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;&#34;&gt;&lt;code class=&#34;language-java&#34; data-lang=&#34;java&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;public&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;class&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;Singleton&lt;/span&gt; {
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;private&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;Singleton&lt;/span&gt;() {
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        &lt;span style=&#34;color:#75715e&#34;&gt;// Prevent reflection attack&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        &lt;span style=&#34;color:#66d9ef&#34;&gt;if&lt;/span&gt; (SingletonHelper.&lt;span style=&#34;color:#a6e22e&#34;&gt;INSTANCE&lt;/span&gt; &lt;span style=&#34;color:#f92672&#34;&gt;!=&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;null&lt;/span&gt;) {
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;            &lt;span style=&#34;color:#66d9ef&#34;&gt;throw&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;new&lt;/span&gt; RuntimeException(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;Use getInstance() method to get the single instance of this class&amp;#34;&lt;/span&gt;);
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        }
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    }
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;private&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;static&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;class&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;SingletonHelper&lt;/span&gt; {
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        &lt;span style=&#34;color:#66d9ef&#34;&gt;private&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;static&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;final&lt;/span&gt; Singleton INSTANCE &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;new&lt;/span&gt; Singleton();
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    }
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;public&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;static&lt;/span&gt; Singleton &lt;span style=&#34;color:#a6e22e&#34;&gt;getInstance&lt;/span&gt;() {
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; SingletonHelper.&lt;span style=&#34;color:#a6e22e&#34;&gt;INSTANCE&lt;/span&gt;;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    }
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;public&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;void&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;example&lt;/span&gt;() {
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        System.&lt;span style=&#34;color:#a6e22e&#34;&gt;out&lt;/span&gt;.&lt;span style=&#34;color:#a6e22e&#34;&gt;println&lt;/span&gt;(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;Hello from Singleton!, (Bill Pugh)&amp;#34;&lt;/span&gt;);
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    }
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;}
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Static inner helper class&lt;/strong&gt; is loaded only when &lt;code&gt;getInstance()&lt;/code&gt; is called.&lt;/li&gt;
&lt;li&gt;Class loading is thread-safe.&lt;/li&gt;
&lt;li&gt;No need for synchronized, and &lt;strong&gt;lazy initialization&lt;/strong&gt; is achieved.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&#34;drawbacks&#34;&gt;Drawbacks&lt;/h3&gt;
&lt;p&gt;Despite its utility, the Singleton pattern is sometimes criticized as an anti-pattern because it can:&lt;/p&gt;</description>
            <content type="html"><![CDATA[<p><strong>Singleton design pattern</strong> is a creational design pattern that restricts instantiation of a class ensuring class has only <strong>one instance</strong> and provide a <strong>global point</strong> of access to it.</p>
<h3 id="common-implementations">Common Implementations</h3>
<ul>
<li><strong>Lazy Initialization</strong>: ensures instance is created only when it is first requested.</li>
<li><strong>Eager Initialization</strong>: instance is created when the class is loaded.</li>
<li><strong>Thread-Safe Implementations</strong>: ensures the singleton works correctly in multi-threaded environments, such as using <code>synchronized</code> methods or double-checked locking.
(though double-checked locking has nuances and is sometimes considered an anti-pattern in modern Java)</li>
</ul>
<h3 id="use-cases">Use Cases</h3>
<ul>
<li>Logging</li>
<li>Configuration settings</li>
<li>Thread pools</li>
<li>Caches</li>
<li>Device drivers</li>
</ul>
<h3 id="examples">Examples</h3>
<h4 id="eager-initialization">Eager initialization</h4>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Singleton</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">final</span> Singleton instance <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> Singleton();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#a6e22e">EagerInitializedSingleton</span>(){}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> Singleton <span style="color:#a6e22e">getInstance</span>() {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> instance;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><ul>
<li>Useful if your singleton class is not using a lot of resources.</li>
</ul>
<h4 id="using-synchronized-method-lazy-initialization">Using <code>synchronized</code> method (Lazy initialization)</h4>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Singleton</span> {
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Volatile ensures visibility and prevents reordering</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">volatile</span> Singleton instance;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#a6e22e">Singleton</span>() {
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Thread-safe with method-level synchronization</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">synchronized</span> Singleton <span style="color:#a6e22e">getInstance</span>() {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (instance <span style="color:#f92672">==</span> <span style="color:#66d9ef">null</span>) {
</span></span><span style="display:flex;"><span>            instance <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> Singleton();
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> instance;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">example</span>() {
</span></span><span style="display:flex;"><span>        System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(<span style="color:#e6db74">&#34;Hello from Singleton!, (using synchronized method)&#34;</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><ul>
<li>Lazily initialization the instance.</li>
<li><code>synchronized</code> ensures that only one thread can enter the method at a time.</li>
<li>It ensures lazy initialization — Singleton instance is created only when needed.</li>
<li>Performance overhead: Every call to <code>getInstance()</code> acquires a lock, even after the instance has been initialized. This is unnecessary and can be expensive under heavy load.</li>
</ul>
<h4 id="double-checked-locking-lazy-initialization">Double-Checked Locking (Lazy initialization)</h4>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Singleton</span> {
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">volatile</span> Singleton instance;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#a6e22e">Singleton</span>() {}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> Singleton <span style="color:#a6e22e">getInstance</span>() {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (instance <span style="color:#f92672">==</span> <span style="color:#66d9ef">null</span>) {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">synchronized</span> (Singleton.<span style="color:#a6e22e">class</span>) {
</span></span><span style="display:flex;"><span>                <span style="color:#66d9ef">if</span> (instance <span style="color:#f92672">==</span> <span style="color:#66d9ef">null</span>) { <span style="color:#75715e">// &lt;- Double-check</span>
</span></span><span style="display:flex;"><span>                    instance <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> Singleton();
</span></span><span style="display:flex;"><span>                }
</span></span><span style="display:flex;"><span>            }
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> instance;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">example</span>() {
</span></span><span style="display:flex;"><span>        System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(<span style="color:#e6db74">&#34;Hello from Singleton!, (double-check)&#34;</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><ul>
<li>Lazily initialization the instance.</li>
<li><strong>double check</strong> aims to minimize the overhead of synchronization.</li>
<li>Complex</li>
</ul>
<h4 id="bill-pugh-inner-class---recommended-approach">Bill Pugh (Inner Class) - Recommended Approach</h4>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Singleton</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#a6e22e">Singleton</span>() {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Prevent reflection attack</span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (SingletonHelper.<span style="color:#a6e22e">INSTANCE</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">null</span>) {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">throw</span> <span style="color:#66d9ef">new</span> RuntimeException(<span style="color:#e6db74">&#34;Use getInstance() method to get the single instance of this class&#34;</span>);
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">SingletonHelper</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">final</span> Singleton INSTANCE <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> Singleton();
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> Singleton <span style="color:#a6e22e">getInstance</span>() {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> SingletonHelper.<span style="color:#a6e22e">INSTANCE</span>;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">example</span>() {
</span></span><span style="display:flex;"><span>        System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(<span style="color:#e6db74">&#34;Hello from Singleton!, (Bill Pugh)&#34;</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><ul>
<li><strong>Static inner helper class</strong> is loaded only when <code>getInstance()</code> is called.</li>
<li>Class loading is thread-safe.</li>
<li>No need for synchronized, and <strong>lazy initialization</strong> is achieved.</li>
</ul>
<h3 id="drawbacks">Drawbacks</h3>
<p>Despite its utility, the Singleton pattern is sometimes criticized as an anti-pattern because it can:</p>
<ul>
<li><strong>Creates global state</strong>: Leading to tight coupling and potential side effects.</li>
<li><strong>Makes Testability difficult</strong>: Making unit testing challenging due to hidden dependencies.</li>
<li><strong>Violate the Single Responsibility Principle</strong>: When the singleton takes on responsibilities beyond managing its own instance.</li>
</ul>
]]></content>
        </item>
        
        <item>
            <title>What&#39;s new in Spring Boot 4.0? A Look Ahead</title>
            <link>https://aamernabi.github.io/posts/spring-boot-4.0/</link>
            <pubDate>Thu, 24 Jul 2025 10:24:00 +0530</pubDate>
            
            <guid>https://aamernabi.github.io/posts/spring-boot-4.0/</guid>
            <description>&lt;p&gt;The Spring ecosystem is constantly evolving to provide developers with the best tools for building modern, robust applications. With the upcoming release of Spring Framework 7.0, the community is eagerly anticipating the next major iteration of Spring Boot: version 4.0.&lt;/p&gt;
&lt;p&gt;Spring Boot 4.0 is a major release of the Spring Boot framework, introducing significant enhancements for developers.&lt;/p&gt;
&lt;p&gt;Key features and improvements in Spring Boot 4 includes:&lt;/p&gt;
&lt;h2 id=&#34;core-enhancements&#34;&gt;Core Enhancements&lt;/h2&gt;
&lt;p&gt;Spring Boot 4.0 is built upon &lt;strong&gt;Spring Framework 7.0&lt;/strong&gt; which is major upcoming release of Spring Framework (projected for General Availability in November 2025).&lt;/p&gt;</description>
            <content type="html"><![CDATA[<p>The Spring ecosystem is constantly evolving to provide developers with the best tools for building modern, robust applications. With the upcoming release of Spring Framework 7.0, the community is eagerly anticipating the next major iteration of Spring Boot: version 4.0.</p>
<p>Spring Boot 4.0 is a major release of the Spring Boot framework, introducing significant enhancements for developers.</p>
<p>Key features and improvements in Spring Boot 4 includes:</p>
<h2 id="core-enhancements">Core Enhancements</h2>
<p>Spring Boot 4.0 is built upon <strong>Spring Framework 7.0</strong> which is major upcoming release of Spring Framework (projected for General Availability in November 2025).</p>
<ol>
<li>
<p><strong>Java 17+ Baseline</strong></p>
<ul>
<li>Spring Boot 4 will <strong>require Java 17 or higher</strong> while at the same time recommending JDK 25 as the latest LTS release.</li>
<li>This baseline enables Spring Boot 4 to leverage the modern features of Java like pattern matching, sealed classes/interfaces, records, virtual threads and includes JVM level performance improvements.</li>
</ul>
</li>
<li>
<p><strong>Jakarta EE 11+</strong></p>
<p>Spring Boot 4 supports Jakarta EE 11 and later, which means you have to move away from older <code>javax.*</code> and use <code>jakarta.*</code> instead.</p>
</li>
<li>
<p><strong>Enhanced Native Compilation with AOT</strong></p>
<p>Spring Boot 4 further refines native image generation using GraalVM and Ahead-of-Time (AOT) processing.</p>
</li>
<li>
<p><strong>Kotlin 2.2+ Support</strong></p>
<p>Spring Boot 4 introduces support for Kotlin 2.2+, enabling developers to leverage the latest features and improvements in the Kotlin language.</p>
</li>
<li>
<p><strong>Micrometer 2.0+ Support</strong></p>
<p>Spring Boot 4 is bundled with Micrometer 2.0+, offering better metrics, and improved observability support.</p>
</li>
<li>
<p><strong>Spring Security 7 Integration</strong></p>
<p>Includes enhanced security with OAuth 2.1 and OpenID Connect protection.</p>
</li>
<li>
<p><strong>Improved Configuration Properties</strong></p>
<p>Includes smarter record-based configuration with native hints for GraalVM and built-in validation.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#a6e22e">@ConfigurationProperties</span>(<span style="color:#e6db74">&#34;app.database&#34;</span>)
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">record</span> <span style="color:#a6e22e">DatabaseProperties</span>(String url, String username, String password, <span style="color:#66d9ef">int</span> poolSize) {}
</span></span></code></pre></div></li>
<li>
<p><strong>Null-Safety Improvements</strong></p>
<p>The framework adopts JSpecify annotations to declare the null-safety of its API.</p>
</li>
</ol>
<h2 id="other-notable-improvements">Other notable improvements</h2>
<h3 id="api-version-control">API Version Control</h3>
<p>The new update introduces streamlined support for API Versioning through annotations. This simplifies API evolution and maintenance.</p>
<p>Example:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-kotlin" data-lang="kotlin"><span style="display:flex;"><span><span style="color:#a6e22e">@RestController</span>()
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">@RequestMapping</span>(<span style="color:#e6db74">&#34;/greet&#34;</span>)
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">DemoController</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">@GetMapping</span>(<span style="color:#e6db74">&#34;&#34;</span>, version = <span style="color:#e6db74">&#34;1&#34;</span>)
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">fun</span> <span style="color:#a6e22e">greetV1</span>(): Map&lt;String, String&gt; = mapOf(<span style="color:#e6db74">&#34;message&#34;</span> to <span style="color:#e6db74">&#34;Hello! from greetV1()&#34;</span>)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">@GetMapping</span>(<span style="color:#e6db74">&#34;&#34;</span>, version = <span style="color:#e6db74">&#34;2&#34;</span>)
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">fun</span> <span style="color:#a6e22e">greetV2</span>(): Map&lt;String, String&gt; = mapOf(<span style="color:#e6db74">&#34;message&#34;</span> to <span style="color:#e6db74">&#34;Hello! from greetV2()&#34;</span>)
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>To make above code work, you need to provide the <code>ApiVersionStrategy</code>. If you run above code without providing <code>ApiVersionStrategy</code>, app will throw:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-bash" data-lang="bash"><span style="display:flex;"><span>Caused by: java.lang.IllegalStateException: API version specified, but no ApiVersionStrategy configured
</span></span></code></pre></div><p>Providing <code>ApiVersionStrategy</code>:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-kotlin" data-lang="kotlin"><span style="display:flex;"><span><span style="color:#a6e22e">@Configuration</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">WebConfiguration</span> : WebMvcConfigurer {
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">override</span> <span style="color:#66d9ef">fun</span> <span style="color:#a6e22e">configureApiVersioning</span>(configurer: ApiVersionConfigurer) {
</span></span><span style="display:flex;"><span>		configurer.useRequestHeader(<span style="color:#e6db74">&#34;X-API-Version&#34;</span>)
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>When calling api you have to provide the request header <code>X-API-Version</code></p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-bash" data-lang="bash"><span style="display:flex;"><span>curl -H <span style="color:#e6db74">&#34;X-API-Version: 2&#34;</span>  http://0.0.0.0:8080/greet
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e"># Response: {&#34;message&#34;:&#34;Hello! from greetV2()&#34;}</span>
</span></span></code></pre></div><h3 id="programmatic-bean-registration-beanregistrar">Programmatic Bean Registration (<code>BeanRegistrar</code>)</h3>
<p>Spring Framework 7.0 introduces a new mechanism to register the bean programmatically using <code>BeanRegistrar</code> interface. This provides a more flexible approach to register a bean.</p>
<p>There are various benefits of providing the bean programmatically, for example, registering a bean based on some runtime conditions like active profiles.</p>
<p>Example:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-kotlin" data-lang="kotlin"><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Foo</span>()
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">data</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Bar</span>(<span style="color:#66d9ef">val</span> value: String)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// you can also use BeanRegistrarDsl in Kotlin
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">FooBarBeanRegistrar</span> : BeanRegistrar {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">override</span> <span style="color:#66d9ef">fun</span> <span style="color:#a6e22e">register</span>(
</span></span><span style="display:flex;"><span>        registry: BeanRegistry,
</span></span><span style="display:flex;"><span>        env: Environment
</span></span><span style="display:flex;"><span>    ) {
</span></span><span style="display:flex;"><span>        registry.registerBean(<span style="color:#e6db74">&#34;foo&#34;</span>, Foo<span style="color:#f92672">::</span><span style="color:#66d9ef">class</span>.java)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Register a bean with a custom supplier, potentially conditionally
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#66d9ef">if</span> (env.matchesProfiles(<span style="color:#e6db74">&#34;dev&#34;</span>)) {
</span></span><span style="display:flex;"><span>            registry.registerBean(Bar<span style="color:#f92672">::</span><span style="color:#66d9ef">class</span>.java) { spec <span style="color:#f92672">-&gt;</span>
</span></span><span style="display:flex;"><span>                spec.supplier { Bar(<span style="color:#e6db74">&#34;Bar_001&#34;</span>) }
</span></span><span style="display:flex;"><span>                    .prototype()
</span></span><span style="display:flex;"><span>                    .lazyInit()
</span></span><span style="display:flex;"><span>                    .description(<span style="color:#e6db74">&#34;Bar 001 description&#34;</span>)
</span></span><span style="display:flex;"><span>            }
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Importing <code>FooBarBeanRegistrar</code></p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-kotlin" data-lang="kotlin"><span style="display:flex;"><span><span style="color:#a6e22e">@Configuration</span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">@Import</span>(FooBarBeanRegistrar<span style="color:#f92672">::</span><span style="color:#66d9ef">class</span>)
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">AppConfig</span>(
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">val</span> foo: Foo,
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">val</span> bar: Bar,
</span></span><span style="display:flex;"><span>) {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">val</span> logger: Logger = <span style="color:#a6e22e">LoggerFactory</span>.getLogger(AppConfig<span style="color:#f92672">::</span><span style="color:#66d9ef">class</span>.java)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">@Bean</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">fun</span> <span style="color:#a6e22e">provideCommandLine</span>(): CommandLineRunner = CommandLineRunner { args <span style="color:#f92672">-&gt;</span>
</span></span><span style="display:flex;"><span>        logger.info(<span style="color:#e6db74">&#34;foo = </span><span style="color:#e6db74">$foo</span><span style="color:#e6db74">&#34;</span>)
</span></span><span style="display:flex;"><span>        logger.info(<span style="color:#e6db74">&#34;bar = </span><span style="color:#e6db74">$bar</span><span style="color:#e6db74">&#34;</span>)
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><h3 id="declarative-http-interface">Declarative HTTP interface</h3>
<p>Spring Boot 4 introduces enhanced support for declarative HTTP clients, building upon the existing <code>RestClient</code> and <code>WebClient</code> options.</p>
<p>It allows defining HTTP client interfaces using annotations, similar to Feign client. Spring generates the implementation at runtime, reducing boilerplate code for making HTTP requests.</p>
<p>Example:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-kotlin" data-lang="kotlin"><span style="display:flex;"><span><span style="color:#a6e22e">@HttpExchange</span>(<span style="color:#e6db74">&#34;https://jsonplaceholder.typicode.com&#34;</span>)
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">TodoClient</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">@GetExchange</span>(<span style="color:#e6db74">&#34;/todos&#34;</span>)
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">fun</span> <span style="color:#a6e22e">getTodos</span>(): List&lt;Todo&gt;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">@GetExchange</span>(<span style="color:#e6db74">&#34;/todos/{id}&#34;</span>)
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">fun</span> <span style="color:#a6e22e">getTodoById</span>(<span style="color:#a6e22e">@PathVariable</span> id: Long): Todo?
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">@PostExchange</span>(<span style="color:#e6db74">&#34;/todos&#34;</span>)
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">fun</span> <span style="color:#a6e22e">createTodo</span>(<span style="color:#a6e22e">@RequestBody</span> todo: Map&lt;String, String&gt;)
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">@Configuration</span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">@ImportHttpServices</span>(TodoClient<span style="color:#f92672">::</span><span style="color:#66d9ef">class</span>)
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">ClientsConfiguration</span>
</span></span></code></pre></div><h2 id="conclusion">Conclusion</h2>
<p>Spring Boot 4 aims to be a transformative release, introducing numerous enhancements to the Spring Framework that significantly simplify application development.</p>
]]></content>
        </item>
        
        <item>
            <title>Controlling Inheritance with Java&#39;s Sealed Classes and Interfaces</title>
            <link>https://aamernabi.github.io/posts/java-sealed-interface/</link>
            <pubDate>Tue, 02 Jul 2024 16:25:32 +0530</pubDate>
            
            <guid>https://aamernabi.github.io/posts/java-sealed-interface/</guid>
            <description>&lt;p&gt;Introduced as a standard feature in Java 17, &lt;strong&gt;sealed classes&lt;/strong&gt; and &lt;strong&gt;sealed interfaces&lt;/strong&gt; give you precise control over your class hierarchies. By declaring a class or interface as &lt;code&gt;sealed&lt;/code&gt;, you can restrict which other classes or interfaces are allowed to extend or implement it.&lt;/p&gt;
&lt;p&gt;This feature is a powerful tool for domain modeling, enhancing security, and working with pattern matching in &lt;code&gt;switch&lt;/code&gt; expressions.&lt;/p&gt;
&lt;h2 id=&#34;what-are-sealed-classes&#34;&gt;What are Sealed Classes?&lt;/h2&gt;
&lt;p&gt;A &lt;strong&gt;sealed class&lt;/strong&gt; restricts which other classes can inherit from it. This provides better control over the class hierarchy, making your code more robust and maintainable.&lt;/p&gt;</description>
            <content type="html"><![CDATA[<p>Introduced as a standard feature in Java 17, <strong>sealed classes</strong> and <strong>sealed interfaces</strong> give you precise control over your class hierarchies. By declaring a class or interface as <code>sealed</code>, you can restrict which other classes or interfaces are allowed to extend or implement it.</p>
<p>This feature is a powerful tool for domain modeling, enhancing security, and working with pattern matching in <code>switch</code> expressions.</p>
<h2 id="what-are-sealed-classes">What are Sealed Classes?</h2>
<p>A <strong>sealed class</strong> restricts which other classes can inherit from it. This provides better control over the class hierarchy, making your code more robust and maintainable.</p>
<p><strong>Syntax:</strong></p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">sealed</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Vehicle</span> permits Car, Truck {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// class body</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>In this example, <code>Vehicle</code> is a sealed class, and only <code>Car</code> and <code>Truck</code> are permitted to extend it.</p>
<h3 id="rules-for-subclasses">Rules for Subclasses</h3>
<p>Any class that extends a sealed class must:</p>
<ol>
<li>Be listed in the <code>permits</code> clause of the sealed class.</li>
<li>Be in the same module or package as the sealed class.</li>
<li>Explicitly declare itself as either:
<ul>
<li><code>final</code>: Cannot be extended further.</li>
<li><code>sealed</code>: Can be extended, but only by the classes it permits.</li>
<li><code>non-sealed</code>: Removes the sealing restriction, allowing any class to extend it.</li>
</ul>
</li>
</ol>
<p><strong>Example Hierarchy:</strong></p>
<p><img src="/sealed-class-in-java.png" alt="image"></p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#75715e">// Car is final and cannot be extended</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">final</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Car</span> <span style="color:#66d9ef">extends</span> Vehicle {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// ...</span>
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Truck is non-sealed, so any class can extend it</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> non<span style="color:#f92672">-</span><span style="color:#66d9ef">sealed</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Truck</span> <span style="color:#66d9ef">extends</span> Vehicle {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// ...</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><h2 id="what-are-sealed-interfaces">What are Sealed Interfaces?</h2>
<p>Similarly, a <strong>sealed interface</strong> restricts which classes or interfaces can implement or extend it.</p>
<p><strong>Syntax:</strong></p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">sealed</span> <span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">Shape</span> permits Circle, Rectangle, Square {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// interface body</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Here, only <code>Circle</code>, <code>Rectangle</code>, and <code>Square</code> are allowed to implement the <code>Shape</code> interface.</p>
<h3 id="rules-for-implementers">Rules for Implementers</h3>
<p>The same rules for subclasses of sealed classes apply to classes that implement a sealed interface. They must be <code>final</code>, <code>sealed</code>, or <code>non-sealed</code>.</p>
<p><strong>Example Hierarchy:</strong></p>
<p><img src="/sealed-interface-in-java.png" alt="image"></p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">final</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Circle</span> <span style="color:#66d9ef">implements</span> Shape { <span style="color:#75715e">/* ... */</span> }
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">final</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Rectangle</span> <span style="color:#66d9ef">implements</span> Shape { <span style="color:#75715e">/* ... */</span> }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// A record is implicitly final</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">record</span> <span style="color:#a6e22e">Square</span>(<span style="color:#66d9ef">int</span> side) <span style="color:#66d9ef">implements</span> Shape { <span style="color:#75715e">/* ... */</span> }
</span></span></code></pre></div><h2 id="sealed-types-and-pattern-matching">Sealed Types and Pattern Matching</h2>
<p>One of the biggest benefits of sealed types is how they enhance <strong>pattern matching</strong> in <code>switch</code> expressions. When you switch over a sealed type, the compiler knows all the permitted subtypes. This allows it to perform an <strong>exhaustive check</strong>, ensuring that you have handled all possible cases.</p>
<p>If you cover all the permitted subtypes, you don&rsquo;t need a <code>default</code> clause, which makes your code safer and more readable.</p>
<h3 id="example-with-an-enhanced-switch">Example with an Enhanced <code>switch</code></h3>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#66d9ef">sealed</span> <span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">Vehicle</span> permits Car, Truck, Bike {}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">final</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Car</span> <span style="color:#66d9ef">implements</span> Vehicle {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">int</span> <span style="color:#a6e22e">getNumberOfSeats</span>() { <span style="color:#66d9ef">return</span> 4; }
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">final</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Truck</span> <span style="color:#66d9ef">implements</span> Vehicle {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">int</span> <span style="color:#a6e22e">getLoadCapacity</span>() { <span style="color:#66d9ef">return</span> 5000; }
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">record</span> <span style="color:#a6e22e">Bike</span>(String type) <span style="color:#66d9ef">implements</span> Vehicle {}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">VehicleProcessor</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> String <span style="color:#a6e22e">processVehicle</span>(Vehicle vehicle) {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// The switch is exhaustive because Vehicle is sealed.</span>
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// No default case is needed.</span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">switch</span> (vehicle) {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">case</span> Car c <span style="color:#f92672">-&gt;</span> <span style="color:#e6db74">&#34;Processing a car with &#34;</span> <span style="color:#f92672">+</span> c.<span style="color:#a6e22e">getNumberOfSeats</span>() <span style="color:#f92672">+</span> <span style="color:#e6db74">&#34; seats.&#34;</span>;
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">case</span> Truck t <span style="color:#f92672">-&gt;</span> <span style="color:#e6db74">&#34;Processing a truck with a load capacity of &#34;</span> <span style="color:#f92672">+</span> t.<span style="color:#a6e22e">getLoadCapacity</span>() <span style="color:#f92672">+</span> <span style="color:#e6db74">&#34; kg.&#34;</span>;
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">case</span> Bike b <span style="color:#f92672">-&gt;</span> <span style="color:#e6db74">&#34;Processing a &#34;</span> <span style="color:#f92672">+</span> b.<span style="color:#a6e22e">type</span>() <span style="color:#f92672">+</span> <span style="color:#e6db74">&#34; bike.&#34;</span>;
</span></span><span style="display:flex;"><span>        };
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">main</span>(String<span style="color:#f92672">[]</span> args) {
</span></span><span style="display:flex;"><span>        System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(processVehicle(<span style="color:#66d9ef">new</span> Car()));
</span></span><span style="display:flex;"><span>        System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(processVehicle(<span style="color:#66d9ef">new</span> Truck()));
</span></span><span style="display:flex;"><span>        System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(processVehicle(<span style="color:#66d9ef">new</span> Bike(<span style="color:#e6db74">&#34;Mountain&#34;</span>)));
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>If a new subtype were added to the <code>Vehicle</code> interface&rsquo;s <code>permits</code> list, the compiler would flag the <code>switch</code> expression as an error until it is updated to handle the new type.</p>
<h2 id="key-benefits-of-sealed-types">Key Benefits of Sealed Types</h2>
<ul>
<li><strong>Controlled Inheritance</strong>: Prevents unintended extensions, making your class hierarchy predictable.</li>
<li><strong>Enhanced Security</strong>: Restricts who can implement sensitive APIs.</li>
<li><strong>Improved Readability</strong>: Clearly defines the intended inheritance structure.</li>
<li><strong>Exhaustive Compiler Checks</strong>: Enables exhaustive checks in <code>switch</code> expressions, eliminating the need for a <code>default</code> case and reducing bugs.</li>
<li><strong>Precise Domain Modeling</strong>: Helps create more accurate and explicit domain models.</li>
<li><strong>Better Maintainability</strong>: Makes code easier to understand, refactor, and evolve.</li>
</ul>
]]></content>
        </item>
        
        <item>
            <title>Understanding Functional Interfaces in Java</title>
            <link>https://aamernabi.github.io/posts/java-functional-interface/</link>
            <pubDate>Tue, 26 Mar 2024 21:25:32 +0530</pubDate>
            
            <guid>https://aamernabi.github.io/posts/java-functional-interface/</guid>
            <description>&lt;p&gt;A &lt;strong&gt;functional interface&lt;/strong&gt; in Java is an interface that contains exactly one abstract method. Introduced in Java 8, they are the backbone of lambda expressions and the Stream API, enabling a more functional style of programming. They are also known as &lt;strong&gt;Single Abstract Method (SAM)&lt;/strong&gt; interfaces.&lt;/p&gt;
&lt;p&gt;To ensure an interface is a functional interface, you can use the &lt;code&gt;@FunctionalInterface&lt;/code&gt; annotation. The compiler will then trigger an error if the interface does not meet the requirements.&lt;/p&gt;</description>
            <content type="html"><![CDATA[<p>A <strong>functional interface</strong> in Java is an interface that contains exactly one abstract method. Introduced in Java 8, they are the backbone of lambda expressions and the Stream API, enabling a more functional style of programming. They are also known as <strong>Single Abstract Method (SAM)</strong> interfaces.</p>
<p>To ensure an interface is a functional interface, you can use the <code>@FunctionalInterface</code> annotation. The compiler will then trigger an error if the interface does not meet the requirements.</p>
<p>Here&rsquo;s a simple example:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#a6e22e">@FunctionalInterface</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">MyFunctionalInterface</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">execute</span>(String message); <span style="color:#75715e">// The single abstract method</span>
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">FunctionalInterfaceExample</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">main</span>(String<span style="color:#f92672">[]</span> args) {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Using a lambda expression to implement the interface</span>
</span></span><span style="display:flex;"><span>        MyFunctionalInterface myLambda <span style="color:#f92672">=</span> (msg) <span style="color:#f92672">-&gt;</span> System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(<span style="color:#e6db74">&#34;Executing: &#34;</span> <span style="color:#f92672">+</span> msg);
</span></span><span style="display:flex;"><span>        myLambda.<span style="color:#a6e22e">execute</span>(<span style="color:#e6db74">&#34;Hello, Functional World!&#34;</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><h2 id="core-functional-interfaces-in-javautilfunction">Core Functional Interfaces in <code>java.util.function</code></h2>
<p>Java 8 introduced a set of standard functional interfaces in the <code>java.util.function</code> package. These are widely used and cover most common use cases. Let&rsquo;s explore the four main ones.</p>
<h3 id="1-consumert">1. <code>Consumer&lt;T&gt;</code></h3>
<p>A <code>Consumer</code> &ldquo;consumes&rdquo; an input value and performs an operation on it without returning any result.</p>
<ul>
<li><strong>Abstract Method</strong>: <code>void accept(T t)</code></li>
<li><strong>Use Case</strong>: Ideal for operations with side effects, such as printing to the console, logging, or modifying an object.</li>
</ul>
<p><strong>Example:</strong></p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#f92672">import</span> java.util.function.Consumer;
</span></span><span style="display:flex;"><span><span style="color:#f92672">import</span> java.util.Arrays;
</span></span><span style="display:flex;"><span><span style="color:#f92672">import</span> java.util.List;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">ConsumerExample</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">main</span>(String<span style="color:#f92672">[]</span> args) {
</span></span><span style="display:flex;"><span>        Consumer<span style="color:#f92672">&lt;</span>String<span style="color:#f92672">&gt;</span> printer <span style="color:#f92672">=</span> s <span style="color:#f92672">-&gt;</span> System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(s);
</span></span><span style="display:flex;"><span>        List<span style="color:#f92672">&lt;</span>String<span style="color:#f92672">&gt;</span> names <span style="color:#f92672">=</span> Arrays.<span style="color:#a6e22e">asList</span>(<span style="color:#e6db74">&#34;Alice&#34;</span>, <span style="color:#e6db74">&#34;Bob&#34;</span>, <span style="color:#e6db74">&#34;Charlie&#34;</span>);
</span></span><span style="display:flex;"><span>        names.<span style="color:#a6e22e">forEach</span>(printer); <span style="color:#75715e">// Prints each name</span>
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><h3 id="2-predicatet">2. <code>Predicate&lt;T&gt;</code></h3>
<p>A <code>Predicate</code> evaluates a condition on an input value and returns a <code>boolean</code> result.</p>
<ul>
<li><strong>Abstract Method</strong>: <code>boolean test(T t)</code></li>
<li><strong>Use Case</strong>: Perfect for filtering data, validation, and conditional checks. It&rsquo;s heavily used in the Stream API&rsquo;s <code>filter()</code> method.</li>
</ul>
<p><strong>Example:</strong></p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#f92672">import</span> java.util.function.Predicate;
</span></span><span style="display:flex;"><span><span style="color:#f92672">import</span> java.util.stream.Stream;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">PredicateExample</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">main</span>(String<span style="color:#f92672">[]</span> args) {
</span></span><span style="display:flex;"><span>        Predicate<span style="color:#f92672">&lt;</span>String<span style="color:#f92672">&gt;</span> isLongerThan5 <span style="color:#f92672">=</span> s <span style="color:#f92672">-&gt;</span> s.<span style="color:#a6e22e">length</span>() <span style="color:#f92672">&gt;</span> 5;
</span></span><span style="display:flex;"><span>        Stream.<span style="color:#a6e22e">of</span>(<span style="color:#e6db74">&#34;Java&#34;</span>, <span style="color:#e6db74">&#34;Python&#34;</span>, <span style="color:#e6db74">&#34;JavaScript&#34;</span>)
</span></span><span style="display:flex;"><span>              .<span style="color:#a6e22e">filter</span>(isLongerThan5)
</span></span><span style="display:flex;"><span>              .<span style="color:#a6e22e">forEach</span>(System.<span style="color:#a6e22e">out</span>::println); <span style="color:#75715e">// Prints &#34;JavaScript&#34;</span>
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><h3 id="3-functiont-r">3. <code>Function&lt;T, R&gt;</code></h3>
<p>A <code>Function</code> takes an input of type <code>T</code> and produces a result of type <code>R</code>. It&rsquo;s used for transformation and mapping.</p>
<ul>
<li><strong>Abstract Method</strong>: <code>R apply(T t)</code></li>
<li><strong>Use Case</strong>: Transforming one object into another, such as converting a <code>String</code> to its length or mapping a DTO to an entity.</li>
</ul>
<p><strong>Example:</strong></p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#f92672">import</span> java.util.function.Function;
</span></span><span style="display:flex;"><span><span style="color:#f92672">import</span> java.util.stream.Stream;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">FunctionExample</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">main</span>(String<span style="color:#f92672">[]</span> args) {
</span></span><span style="display:flex;"><span>        Function<span style="color:#f92672">&lt;</span>String, Integer<span style="color:#f92672">&gt;</span> stringLength <span style="color:#f92672">=</span> s <span style="color:#f92672">-&gt;</span> s.<span style="color:#a6e22e">length</span>();
</span></span><span style="display:flex;"><span>        Stream.<span style="color:#a6e22e">of</span>(<span style="color:#e6db74">&#34;Apple&#34;</span>, <span style="color:#e6db74">&#34;Banana&#34;</span>, <span style="color:#e6db74">&#34;Cherry&#34;</span>)
</span></span><span style="display:flex;"><span>              .<span style="color:#a6e22e">map</span>(stringLength)
</span></span><span style="display:flex;"><span>              .<span style="color:#a6e22e">forEach</span>(System.<span style="color:#a6e22e">out</span>::println); <span style="color:#75715e">// Prints 5, 6, 6</span>
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><h3 id="4-suppliert">4. <code>Supplier&lt;T&gt;</code></h3>
<p>A <code>Supplier</code> &ldquo;supplies&rdquo; a value of type <code>T</code> without taking any input.</p>
<ul>
<li><strong>Abstract Method</strong>: <code>T get()</code></li>
<li><strong>Use Case</strong>: Useful for lazy generation of values, such as creating new objects, generating random numbers, or providing default values.</li>
</ul>
<p><strong>Example:</strong></p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#f92672">import</span> java.util.function.Supplier;
</span></span><span style="display:flex;"><span><span style="color:#f92672">import</span> java.time.LocalDateTime;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">SupplierExample</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">main</span>(String<span style="color:#f92672">[]</span> args) {
</span></span><span style="display:flex;"><span>        Supplier<span style="color:#f92672">&lt;</span>LocalDateTime<span style="color:#f92672">&gt;</span> currentTimeSupplier <span style="color:#f92672">=</span> () <span style="color:#f92672">-&gt;</span> LocalDateTime.<span style="color:#a6e22e">now</span>();
</span></span><span style="display:flex;"><span>        System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(currentTimeSupplier.<span style="color:#a6e22e">get</span>()); <span style="color:#75715e">// Prints the current date and time</span>
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>By understanding and using these core functional interfaces, you can write more expressive, concise, and powerful Java code.</p>
]]></content>
        </item>
        
        <item>
            <title>A Deep Dive into the Java Stream API</title>
            <link>https://aamernabi.github.io/posts/deep-dive-into-java-stream-api/</link>
            <pubDate>Mon, 07 Jun 2021 18:12:23 +0530</pubDate>
            
            <guid>https://aamernabi.github.io/posts/deep-dive-into-java-stream-api/</guid>
            <description>&lt;p&gt;The &lt;strong&gt;Stream API&lt;/strong&gt;, introduced in Java 8, is a powerful tool for processing sequences of elements. It provides a functional approach to working with collections and arrays, allowing for expressive and efficient data manipulation. Streams don&amp;rsquo;t store data; instead, they operate on a data source, such as a &lt;code&gt;Collection&lt;/code&gt; or an array, and enable aggregate operations.&lt;/p&gt;
&lt;h2 id=&#34;core-concepts&#34;&gt;Core Concepts&lt;/h2&gt;
&lt;p&gt;A stream pipeline consists of three parts:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;A source&lt;/strong&gt;: Where the stream originates from (e.g., a &lt;code&gt;List&lt;/code&gt;, &lt;code&gt;Set&lt;/code&gt;, or array).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Zero or more intermediate operations&lt;/strong&gt;: These transform the stream into another stream. Examples include &lt;code&gt;filter&lt;/code&gt;, &lt;code&gt;map&lt;/code&gt;, and &lt;code&gt;sorted&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A terminal operation&lt;/strong&gt;: This produces a result or a side-effect, and triggers the execution of the pipeline. Examples include &lt;code&gt;forEach&lt;/code&gt;, &lt;code&gt;collect&lt;/code&gt;, and &lt;code&gt;reduce&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;One of the key features of streams is &lt;strong&gt;laziness&lt;/strong&gt;. Intermediate operations are not executed until a terminal operation is invoked. This allows the Stream API to optimize the execution of the pipeline.&lt;/p&gt;</description>
            <content type="html"><![CDATA[<p>The <strong>Stream API</strong>, introduced in Java 8, is a powerful tool for processing sequences of elements. It provides a functional approach to working with collections and arrays, allowing for expressive and efficient data manipulation. Streams don&rsquo;t store data; instead, they operate on a data source, such as a <code>Collection</code> or an array, and enable aggregate operations.</p>
<h2 id="core-concepts">Core Concepts</h2>
<p>A stream pipeline consists of three parts:</p>
<ol>
<li><strong>A source</strong>: Where the stream originates from (e.g., a <code>List</code>, <code>Set</code>, or array).</li>
<li><strong>Zero or more intermediate operations</strong>: These transform the stream into another stream. Examples include <code>filter</code>, <code>map</code>, and <code>sorted</code>.</li>
<li><strong>A terminal operation</strong>: This produces a result or a side-effect, and triggers the execution of the pipeline. Examples include <code>forEach</code>, <code>collect</code>, and <code>reduce</code>.</li>
</ol>
<p>One of the key features of streams is <strong>laziness</strong>. Intermediate operations are not executed until a terminal operation is invoked. This allows the Stream API to optimize the execution of the pipeline.</p>
<h2 id="creating-streams">Creating Streams</h2>
<p>There are several ways to create a stream:</p>
<h3 id="from-a-collection">From a Collection</h3>
<p>You can create a stream from any <code>Collection</code> (e.g., <code>List</code>, <code>Set</code>) using the <code>stream()</code> method.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span>List<span style="color:#f92672">&lt;</span>String<span style="color:#f92672">&gt;</span> names <span style="color:#f92672">=</span> Arrays.<span style="color:#a6e22e">asList</span>(<span style="color:#e6db74">&#34;Alice&#34;</span>, <span style="color:#e6db74">&#34;Bob&#34;</span>, <span style="color:#e6db74">&#34;Charlie&#34;</span>);
</span></span><span style="display:flex;"><span>Stream<span style="color:#f92672">&lt;</span>String<span style="color:#f92672">&gt;</span> nameStream <span style="color:#f92672">=</span> names.<span style="color:#a6e22e">stream</span>();
</span></span></code></pre></div><h3 id="from-an-array">From an Array</h3>
<p>You can create a stream from an array using the <code>Arrays.stream()</code> method or <code>Stream.of()</code>.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span>String<span style="color:#f92672">[]</span> nameArray <span style="color:#f92672">=</span> {<span style="color:#e6db74">&#34;Alice&#34;</span>, <span style="color:#e6db74">&#34;Bob&#34;</span>, <span style="color:#e6db74">&#34;Charlie&#34;</span>};
</span></span><span style="display:flex;"><span>Stream<span style="color:#f92672">&lt;</span>String<span style="color:#f92672">&gt;</span> nameStreamFromArray <span style="color:#f92672">=</span> Arrays.<span style="color:#a6e22e">stream</span>(nameArray);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>Stream<span style="color:#f92672">&lt;</span>String<span style="color:#f92672">&gt;</span> nameStreamFromOf <span style="color:#f92672">=</span> Stream.<span style="color:#a6e22e">of</span>(<span style="color:#e6db74">&#34;Alice&#34;</span>, <span style="color:#e6db74">&#34;Bob&#34;</span>, <span style="color:#e6db74">&#34;Charlie&#34;</span>);
</span></span></code></pre></div><h3 id="from-a-range-of-numbers">From a Range of Numbers</h3>
<p>The <code>IntStream</code>, <code>LongStream</code>, and <code>DoubleStream</code> interfaces provide methods for creating streams of primitive numeric types.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span>IntStream intStream <span style="color:#f92672">=</span> IntStream.<span style="color:#a6e22e">range</span>(1, 5); <span style="color:#75715e">// 1, 2, 3, 4</span>
</span></span><span style="display:flex;"><span>LongStream longStream <span style="color:#f92672">=</span> LongStream.<span style="color:#a6e22e">rangeClosed</span>(1, 5); <span style="color:#75715e">// 1, 2, 3, 4, 5</span>
</span></span></code></pre></div><h3 id="using-streamiterate-and-streamgenerate">Using <code>Stream.iterate()</code> and <code>Stream.generate()</code></h3>
<p>You can also create infinite streams using <code>iterate()</code> and <code>generate()</code>.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span>Stream<span style="color:#f92672">&lt;</span>Integer<span style="color:#f92672">&gt;</span> evenNumbers <span style="color:#f92672">=</span> Stream.<span style="color:#a6e22e">iterate</span>(0, n <span style="color:#f92672">-&gt;</span> n <span style="color:#f92672">+</span> 2);
</span></span><span style="display:flex;"><span>Stream<span style="color:#f92672">&lt;</span>Double<span style="color:#f92672">&gt;</span> randomNumbers <span style="color:#f92672">=</span> Stream.<span style="color:#a6e22e">generate</span>(Math::random);
</span></span></code></pre></div><p>It&rsquo;s important to use <code>limit()</code> with infinite streams to prevent an infinite loop.</p>
<h2 id="stream-operations">Stream Operations</h2>
<p>Stream operations are divided into two categories: intermediate and terminal.</p>
<h3 id="intermediate-operations">Intermediate Operations</h3>
<p>Intermediate operations return a new stream and are always lazy.</p>
<ul>
<li>
<p><strong><code>filter(Predicate&lt;T&gt;)</code></strong>: Returns a stream consisting of the elements of this stream that match the given predicate.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span>List<span style="color:#f92672">&lt;</span>String<span style="color:#f92672">&gt;</span> names <span style="color:#f92672">=</span> Arrays.<span style="color:#a6e22e">asList</span>(<span style="color:#e6db74">&#34;Alice&#34;</span>, <span style="color:#e6db74">&#34;Bob&#34;</span>, <span style="color:#e6db74">&#34;Charlie&#34;</span>, <span style="color:#e6db74">&#34;Anna&#34;</span>);
</span></span><span style="display:flex;"><span>names.<span style="color:#a6e22e">stream</span>()
</span></span><span style="display:flex;"><span>     .<span style="color:#a6e22e">filter</span>(name <span style="color:#f92672">-&gt;</span> name.<span style="color:#a6e22e">startsWith</span>(<span style="color:#e6db74">&#34;A&#34;</span>))
</span></span><span style="display:flex;"><span>     .<span style="color:#a6e22e">forEach</span>(System.<span style="color:#a6e22e">out</span>::println); <span style="color:#75715e">// Alice, Anna</span>
</span></span></code></pre></div></li>
<li>
<p><strong><code>map(Function&lt;T, R&gt;)</code></strong>: Returns a stream consisting of the results of applying the given function to the elements of this stream.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span>List<span style="color:#f92672">&lt;</span>String<span style="color:#f92672">&gt;</span> names <span style="color:#f92672">=</span> Arrays.<span style="color:#a6e22e">asList</span>(<span style="color:#e6db74">&#34;Alice&#34;</span>, <span style="color:#e6db74">&#34;Bob&#34;</span>, <span style="color:#e6db74">&#34;Charlie&#34;</span>);
</span></span><span style="display:flex;"><span>names.<span style="color:#a6e22e">stream</span>()
</span></span><span style="display:flex;"><span>     .<span style="color:#a6e22e">map</span>(String::length)
</span></span><span style="display:flex;"><span>     .<span style="color:#a6e22e">forEach</span>(System.<span style="color:#a6e22e">out</span>::println); <span style="color:#75715e">// 5, 3, 7</span>
</span></span></code></pre></div></li>
<li>
<p><strong><code>flatMap(Function&lt;T, Stream&lt;R&gt;&gt;)</code></strong>: Transforms each element of the stream into a stream of other objects and then flattens all the generated streams into a single stream.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span>List<span style="color:#f92672">&lt;</span>List<span style="color:#f92672">&lt;</span>Integer<span style="color:#f92672">&gt;&gt;</span> listOfLists <span style="color:#f92672">=</span> Arrays.<span style="color:#a6e22e">asList</span>(
</span></span><span style="display:flex;"><span>    Arrays.<span style="color:#a6e22e">asList</span>(1, 2),
</span></span><span style="display:flex;"><span>    Arrays.<span style="color:#a6e22e">asList</span>(3, 4),
</span></span><span style="display:flex;"><span>    Arrays.<span style="color:#a6e22e">asList</span>(5, 6)
</span></span><span style="display:flex;"><span>);
</span></span><span style="display:flex;"><span>listOfLists.<span style="color:#a6e22e">stream</span>()
</span></span><span style="display:flex;"><span>           .<span style="color:#a6e22e">flatMap</span>(List::stream)
</span></span><span style="display:flex;"><span>           .<span style="color:#a6e22e">forEach</span>(System.<span style="color:#a6e22e">out</span>::print); <span style="color:#75715e">// 123456</span>
</span></span></code></pre></div></li>
<li>
<p><strong><code>distinct()</code></strong>: Returns a stream consisting of the distinct elements (according to <code>Object.equals(Object)</code>) of this stream.</p>
</li>
<li>
<p><strong><code>sorted()</code></strong>: Returns a stream consisting of the elements of this stream, sorted according to natural order.</p>
</li>
<li>
<p><strong><code>peek(Consumer&lt;T&gt;)</code></strong>: Returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream. This is useful for debugging.</p>
</li>
</ul>
<h3 id="terminal-operations">Terminal Operations</h3>
<p>Terminal operations trigger the stream processing and produce a result.</p>
<ul>
<li>
<p><strong><code>forEach(Consumer&lt;T&gt;)</code></strong>: Performs an action for each element of this stream.</p>
</li>
<li>
<p><strong><code>collect(Collector&lt;T, A, R&gt;)</code></strong>: Performs a mutable reduction operation on the elements of this stream using a <code>Collector</code>. This is one of the most powerful terminal operations.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span>List<span style="color:#f92672">&lt;</span>String<span style="color:#f92672">&gt;</span> names <span style="color:#f92672">=</span> Arrays.<span style="color:#a6e22e">asList</span>(<span style="color:#e6db74">&#34;Alice&#34;</span>, <span style="color:#e6db74">&#34;Bob&#34;</span>, <span style="color:#e6db74">&#34;Charlie&#34;</span>);
</span></span><span style="display:flex;"><span>List<span style="color:#f92672">&lt;</span>String<span style="color:#f92672">&gt;</span> upperCaseNames <span style="color:#f92672">=</span> names.<span style="color:#a6e22e">stream</span>()
</span></span><span style="display:flex;"><span>                                   .<span style="color:#a6e22e">map</span>(String::toUpperCase)
</span></span><span style="display:flex;"><span>                                   .<span style="color:#a6e22e">collect</span>(Collectors.<span style="color:#a6e22e">toList</span>());
</span></span></code></pre></div></li>
<li>
<p><strong><code>reduce(T identity, BinaryOperator&lt;T&gt; accumulator)</code></strong>: Performs a reduction on the elements of this stream, using an initial value and an associative accumulation function.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span>List<span style="color:#f92672">&lt;</span>Integer<span style="color:#f92672">&gt;</span> numbers <span style="color:#f92672">=</span> Arrays.<span style="color:#a6e22e">asList</span>(1, 2, 3, 4, 5);
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">int</span> sum <span style="color:#f92672">=</span> numbers.<span style="color:#a6e22e">stream</span>().<span style="color:#a6e22e">reduce</span>(0, (a, b) <span style="color:#f92672">-&gt;</span> a <span style="color:#f92672">+</span> b); <span style="color:#75715e">// 15</span>
</span></span></code></pre></div></li>
<li>
<p><strong><code>count()</code></strong>: Returns the count of elements in this stream.</p>
</li>
<li>
<p><strong><code>anyMatch(Predicate&lt;T&gt;)</code></strong>, <strong><code>allMatch(Predicate&lt;T&gt;)</code></strong>, <strong><code>noneMatch(Predicate&lt;T&gt;)</code></strong>: These operations check if any, all, or no elements of this stream match the given predicate.</p>
</li>
<li>
<p><strong><code>findFirst()</code></strong>, <strong><code>findAny()</code></strong>: Return an <code>Optional</code> describing the first element of this stream, or an arbitrary element of the stream, respectively.</p>
</li>
</ul>
<h2 id="collectors">Collectors</h2>
<p>The <code>Collectors</code> class provides a set of static factory methods for creating <code>Collector</code> instances.</p>
<ul>
<li><strong><code>toList()</code></strong>, <strong><code>toSet()</code></strong>, <strong><code>toMap()</code></strong>: Collect elements into a <code>List</code>, <code>Set</code>, or <code>Map</code>.</li>
<li><strong><code>joining(CharSequence delimiter)</code></strong>: Joins the elements into a <code>String</code>.</li>
<li><strong><code>groupingBy(Function&lt;T, K&gt;)</code></strong>: Groups elements according to a classification function.</li>
<li><strong><code>partitioningBy(Predicate&lt;T&gt;)</code></strong>: Partitions elements into a <code>Map&lt;Boolean, List&lt;T&gt;&gt;</code> based on a predicate.</li>
</ul>
<h2 id="parallel-streams">Parallel Streams</h2>
<p>You can easily create a parallel stream by calling the <code>parallelStream()</code> method on a collection or by calling the <code>parallel()</code> intermediate method on a stream. This can lead to significant performance improvements for large datasets, as the operations are performed concurrently.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span>List<span style="color:#f92672">&lt;</span>Integer<span style="color:#f92672">&gt;</span> numbers <span style="color:#f92672">=</span> Arrays.<span style="color:#a6e22e">asList</span>(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">int</span> sum <span style="color:#f92672">=</span> numbers.<span style="color:#a6e22e">parallelStream</span>()
</span></span><span style="display:flex;"><span>                 .<span style="color:#a6e22e">mapToInt</span>(Integer::intValue)
</span></span><span style="display:flex;"><span>                 .<span style="color:#a6e22e">sum</span>();
</span></span></code></pre></div><p>However, be mindful of the overhead of parallelism. For small datasets or simple operations, a sequential stream might be faster.</p>
<h2 id="conclusion">Conclusion</h2>
<p>The Java Stream API is a fundamental part of modern Java development. It enables you to write more concise, readable, and potentially more performant code for data processing. By understanding the core concepts of stream creation, intermediate operations, and terminal operations, you can leverage the full power of functional-style programming in Java.</p>
]]></content>
        </item>
        
        <item>
            <title>Thread-Safe Counters in Java: A Deep Dive into AtomicInteger</title>
            <link>https://aamernabi.github.io/posts/thread-safe_counters_in_java_atomicinteger/</link>
            <pubDate>Tue, 19 Jan 2021 10:41:26 +0530</pubDate>
            
            <guid>https://aamernabi.github.io/posts/thread-safe_counters_in_java_atomicinteger/</guid>
            <description>&lt;p&gt;When building multithreaded applications in Java, ensuring data integrity is crucial. A common challenge arises when multiple threads need to update a shared counter. Without proper synchronization, you can encounter race conditions, leading to incorrect results. This is where &lt;code&gt;AtomicInteger&lt;/code&gt; comes to the rescue.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;AtomicInteger&lt;/code&gt; is a class from the &lt;code&gt;java.util.concurrent.atomic&lt;/code&gt; package that provides a thread-safe way to perform atomic operations on an integer value. Unlike traditional locking mechanisms (e.g., &lt;code&gt;synchronized&lt;/code&gt; blocks), &lt;code&gt;AtomicInteger&lt;/code&gt; uses low-level hardware instructions to achieve thread safety with higher performance.&lt;/p&gt;</description>
            <content type="html"><![CDATA[<p>When building multithreaded applications in Java, ensuring data integrity is crucial. A common challenge arises when multiple threads need to update a shared counter. Without proper synchronization, you can encounter race conditions, leading to incorrect results. This is where <code>AtomicInteger</code> comes to the rescue.</p>
<p><code>AtomicInteger</code> is a class from the <code>java.util.concurrent.atomic</code> package that provides a thread-safe way to perform atomic operations on an integer value. Unlike traditional locking mechanisms (e.g., <code>synchronized</code> blocks), <code>AtomicInteger</code> uses low-level hardware instructions to achieve thread safety with higher performance.</p>
<h3 id="the-problem-race-conditions-with-standard-integers">The Problem: Race Conditions with Standard Integers</h3>
<p>In a multithreaded environment, incrementing a simple <code>int</code> variable is not an atomic operation. The seemingly simple <code>counter++</code> operation involves three distinct steps:</p>
<ol>
<li><strong>Read:</strong> Read the current value of the counter.</li>
<li><strong>Modify:</strong> Increment the value.</li>
<li><strong>Write:</strong> Write the updated value back to the counter.</li>
</ol>
<p>If two threads execute this operation simultaneously, they might both read the same initial value, increment it, and write back the same result. This leads to &ldquo;lost updates&rdquo; and an incorrect final value.</p>
<h4 id="non-atomic-example">Non-Atomic Example</h4>
<p>The following code demonstrates this problem. We start ten threads, and each thread increments a shared counter 10,000 times. We expect the final value to be 100,000, but the actual result is often lower due to race conditions.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#f92672">import</span> java.util.concurrent.atomic.AtomicInteger;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">CounterExample</span> {
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">int</span> counter <span style="color:#f92672">=</span> 0;
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">static</span> AtomicInteger atomicCounter <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> AtomicInteger(0);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">main</span>(String<span style="color:#f92672">[]</span> args) <span style="color:#66d9ef">throws</span> InterruptedException {
</span></span><span style="display:flex;"><span>        nonAtomicExample();
</span></span><span style="display:flex;"><span>        atomicExample();
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">nonAtomicExample</span>() <span style="color:#66d9ef">throws</span> InterruptedException {
</span></span><span style="display:flex;"><span>        counter <span style="color:#f92672">=</span> 0;
</span></span><span style="display:flex;"><span>        Runnable task <span style="color:#f92672">=</span> () <span style="color:#f92672">-&gt;</span> {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">for</span> (<span style="color:#66d9ef">int</span> i <span style="color:#f92672">=</span> 0; i <span style="color:#f92672">&lt;</span> 10_000; i<span style="color:#f92672">++</span>) {
</span></span><span style="display:flex;"><span>                counter<span style="color:#f92672">++</span>;
</span></span><span style="display:flex;"><span>            }
</span></span><span style="display:flex;"><span>        };
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        Thread<span style="color:#f92672">[]</span> threads <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> Thread<span style="color:#f92672">[</span>10<span style="color:#f92672">]</span>;
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">for</span> (<span style="color:#66d9ef">int</span> i <span style="color:#f92672">=</span> 0; i <span style="color:#f92672">&lt;</span> 10; i<span style="color:#f92672">++</span>) {
</span></span><span style="display:flex;"><span>            threads<span style="color:#f92672">[</span>i<span style="color:#f92672">]</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> Thread(task);
</span></span><span style="display:flex;"><span>            threads<span style="color:#f92672">[</span>i<span style="color:#f92672">]</span>.<span style="color:#a6e22e">start</span>();
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">for</span> (Thread thread : threads) {
</span></span><span style="display:flex;"><span>            thread.<span style="color:#a6e22e">join</span>();
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(<span style="color:#e6db74">&#34;Non-Atomic Final Counter: &#34;</span> <span style="color:#f92672">+</span> counter);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">atomicExample</span>() <span style="color:#66d9ef">throws</span> InterruptedException {
</span></span><span style="display:flex;"><span>        atomicCounter.<span style="color:#a6e22e">set</span>(0);
</span></span><span style="display:flex;"><span>        Runnable task <span style="color:#f92672">=</span> () <span style="color:#f92672">-&gt;</span> {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">for</span> (<span style="color:#66d9ef">int</span> i <span style="color:#f92672">=</span> 0; i <span style="color:#f92672">&lt;</span> 10_000; i<span style="color:#f92672">++</span>) {
</span></span><span style="display:flex;"><span>                atomicCounter.<span style="color:#a6e22e">incrementAndGet</span>(); <span style="color:#75715e">// Atomic operation</span>
</span></span><span style="display:flex;"><span>            }
</span></span><span style="display:flex;"><span>        };
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        Thread<span style="color:#f92672">[]</span> threads <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> Thread<span style="color:#f92672">[</span>10<span style="color:#f92672">]</span>;
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">for</span> (<span style="color:#66d9ef">int</span> i <span style="color:#f92672">=</span> 0; i <span style="color:#f92672">&lt;</span> 10; i<span style="color:#f92672">++</span>) {
</span></span><span style="display:flex;"><span>            threads<span style="color:#f92672">[</span>i<span style="color:#f92672">]</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> Thread(task);
</span></span><span style="display:flex;"><span>            threads<span style="color:#f92672">[</span>i<span style="color:#f92672">]</span>.<span style="color:#a6e22e">start</span>();
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">for</span> (Thread thread : threads) {
</span></span><span style="display:flex;"><span>            thread.<span style="color:#a6e22e">join</span>();
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(<span style="color:#e6db74">&#34;Atomic Final Counter: &#34;</span> <span style="color:#f92672">+</span> atomicCounter.<span style="color:#a6e22e">get</span>());
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><h3 id="the-solution-atomicinteger">The Solution: <code>AtomicInteger</code></h3>
<p><code>AtomicInteger</code> solves this problem by providing atomic methods for updating the integer value. These methods use a hardware-level mechanism called <strong>Compare-and-Swap (CAS)</strong>.</p>
<h4 id="how-compare-and-swap-cas-works">How Compare-and-Swap (CAS) Works</h4>
<p>CAS is an atomic instruction that compares the contents of a memory location with a given value and, only if they are the same, modifies the contents of that memory location to a new given value. This is done as a single atomic operation.</p>
<p>The <code>incrementAndGet()</code> method, for example, uses CAS to ensure that the read-modify-write operation is atomic. It repeatedly tries to update the value until it succeeds, preventing race conditions.</p>
<h3 id="common-atomicinteger-methods">Common <code>AtomicInteger</code> Methods</h3>
<p>Here are some of the most commonly used methods in <code>AtomicInteger</code>:</p>
<ul>
<li><code>get()</code>: Returns the current value.</li>
<li><code>set(int newValue)</code>: Sets the value to <code>newValue</code>.</li>
<li><code>incrementAndGet()</code>: Atomically increments the current value by one and returns the new value.</li>
<li><code>getAndIncrement()</code>: Atomically increments the current value by one and returns the old value.</li>
<li><code>decrementAndGet()</code>: Atomically decrements the current value by one and returns the new value.</li>
<li><code>getAndDecrement()</code>: Atomically decrements the current value by one and returns the old value.</li>
<li><code>addAndGet(int delta)</code>: Atomically adds the given value to the current value and returns the new value.</li>
<li><code>getAndSet(int newValue)</code>: Atomically sets to the given value and returns the old value.</li>
<li><code>compareAndSet(int expect, int update)</code>: Atomically sets the value to <code>update</code> if the current value is equal to <code>expect</code>, and returns <code>true</code> if successful.</li>
</ul>
<p>By using <code>AtomicInteger</code>, you can ensure the correctness of your multithreaded code without the performance overhead of traditional synchronization.</p>
]]></content>
        </item>
        
        <item>
            <title>A Deep Dive into Java&#39;s BlockingQueue</title>
            <link>https://aamernabi.github.io/posts/java-blocking-queue/</link>
            <pubDate>Mon, 27 Jul 2020 20:09:10 +0530</pubDate>
            
            <guid>https://aamernabi.github.io/posts/java-blocking-queue/</guid>
            <description>&lt;p&gt;A &lt;code&gt;BlockingQueue&lt;/code&gt; in Java is a thread-safe queue that simplifies concurrency management by providing blocking operations. It&amp;rsquo;s a crucial tool for building robust multi-threaded applications, especially for implementing producer-consumer scenarios.&lt;/p&gt;
&lt;h2 id=&#34;why-do-we-need-blockingqueue&#34;&gt;Why Do We Need &lt;code&gt;BlockingQueue&lt;/code&gt;?&lt;/h2&gt;
&lt;p&gt;In multi-threaded applications, it&amp;rsquo;s common to have a scenario where one or more threads (Producers) are generating data, and one or more other threads (Consumers) are processing that data. This is known as the &lt;strong&gt;producer-consumer problem&lt;/strong&gt;.&lt;/p&gt;</description>
            <content type="html"><![CDATA[<p>A <code>BlockingQueue</code> in Java is a thread-safe queue that simplifies concurrency management by providing blocking operations. It&rsquo;s a crucial tool for building robust multi-threaded applications, especially for implementing producer-consumer scenarios.</p>
<h2 id="why-do-we-need-blockingqueue">Why Do We Need <code>BlockingQueue</code>?</h2>
<p>In multi-threaded applications, it&rsquo;s common to have a scenario where one or more threads (Producers) are generating data, and one or more other threads (Consumers) are processing that data. This is known as the <strong>producer-consumer problem</strong>.</p>
<p>A <code>BlockingQueue</code> elegantly solves this by providing a shared, thread-safe channel for communication. Instead of manually implementing complex synchronization logic with <code>wait()</code> and <code>notify()</code>, you can rely on the queue to handle it for you:</p>
<ul>
<li><strong>Blocks Producers:</strong> If the queue is full, any producer thread trying to add an element will be blocked until there is space available.</li>
<li><strong>Blocks Consumers:</strong> If the queue is empty, any consumer thread trying to retrieve an element will be blocked until an item is available.</li>
</ul>
<p>This built-in mechanism simplifies code, reduces the risk of concurrency bugs like race conditions, and improves overall application stability.</p>
<h2 id="the-producer-consumer-pattern-with-blockingqueue">The Producer-Consumer Pattern with <code>BlockingQueue</code></h2>
<p>The producer-consumer pattern is a classic concurrency design pattern. <code>BlockingQueue</code> makes implementing it straightforward.</p>
<p>Here’s a simple example using <code>LinkedBlockingQueue</code>:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#f92672">import</span> java.util.concurrent.BlockingQueue;
</span></span><span style="display:flex;"><span><span style="color:#f92672">import</span> java.util.concurrent.LinkedBlockingQueue;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">BlockingQueueExample</span> {
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">main</span>(String<span style="color:#f92672">[]</span> args) {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// A queue with a fixed capacity of 5</span>
</span></span><span style="display:flex;"><span>        BlockingQueue<span style="color:#f92672">&lt;</span>String<span style="color:#f92672">&gt;</span> queue <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> LinkedBlockingQueue<span style="color:#f92672">&lt;&gt;</span>(5);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Producer thread</span>
</span></span><span style="display:flex;"><span>        Thread producer <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> Thread(() <span style="color:#f92672">-&gt;</span> {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">try</span> {
</span></span><span style="display:flex;"><span>                <span style="color:#66d9ef">for</span> (<span style="color:#66d9ef">int</span> i <span style="color:#f92672">=</span> 1; i <span style="color:#f92672">&lt;=</span> 10; i<span style="color:#f92672">++</span>) {
</span></span><span style="display:flex;"><span>                    String item <span style="color:#f92672">=</span> <span style="color:#e6db74">&#34;Item &#34;</span> <span style="color:#f92672">+</span> i;
</span></span><span style="display:flex;"><span>                    System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(<span style="color:#e6db74">&#34;Producing: &#34;</span> <span style="color:#f92672">+</span> item);
</span></span><span style="display:flex;"><span>                    <span style="color:#75715e">// put() blocks if the queue is full</span>
</span></span><span style="display:flex;"><span>                    queue.<span style="color:#a6e22e">put</span>(item);
</span></span><span style="display:flex;"><span>                    Thread.<span style="color:#a6e22e">sleep</span>(500); <span style="color:#75715e">// Simulate time taken to produce an item</span>
</span></span><span style="display:flex;"><span>                }
</span></span><span style="display:flex;"><span>            } <span style="color:#66d9ef">catch</span> (InterruptedException e) {
</span></span><span style="display:flex;"><span>                Thread.<span style="color:#a6e22e">currentThread</span>().<span style="color:#a6e22e">interrupt</span>();
</span></span><span style="display:flex;"><span>            }
</span></span><span style="display:flex;"><span>        });
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Consumer thread</span>
</span></span><span style="display:flex;"><span>        Thread consumer <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> Thread(() <span style="color:#f92672">-&gt;</span> {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">try</span> {
</span></span><span style="display:flex;"><span>                <span style="color:#66d9ef">for</span> (<span style="color:#66d9ef">int</span> i <span style="color:#f92672">=</span> 1; i <span style="color:#f92672">&lt;=</span> 10; i<span style="color:#f92672">++</span>) {
</span></span><span style="display:flex;"><span>                    <span style="color:#75715e">// take() blocks if the queue is empty</span>
</span></span><span style="display:flex;"><span>                    String item <span style="color:#f92672">=</span> queue.<span style="color:#a6e22e">take</span>();
</span></span><span style="display:flex;"><span>                    System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(<span style="color:#e6db74">&#34;Consuming: &#34;</span> <span style="color:#f92672">+</span> item);
</span></span><span style="display:flex;"><span>                    Thread.<span style="color:#a6e22e">sleep</span>(1000); <span style="color:#75715e">// Simulate time taken to consume an item</span>
</span></span><span style="display:flex;"><span>                }
</span></span><span style="display:flex;"><span>            } <span style="color:#66d9ef">catch</span> (InterruptedException e) {
</span></span><span style="display:flex;"><span>                Thread.<span style="color:#a6e22e">currentThread</span>().<span style="color:#a6e22e">interrupt</span>();
</span></span><span style="display:flex;"><span>            }
</span></span><span style="display:flex;"><span>        });
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        producer.<span style="color:#a6e22e">start</span>();
</span></span><span style="display:flex;"><span>        consumer.<span style="color:#a6e22e">start</span>();
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>In this example:</p>
<ul>
<li>The <code>producer</code> adds items to the queue. If the queue reaches its capacity of 5, the <code>put()</code> call will block until the consumer takes an item.</li>
<li>The <code>consumer</code> removes items. If the queue is empty, the <code>take()</code> call will block until the producer adds an item.</li>
</ul>
<h2 id="common-blockingqueue-implementations">Common <code>BlockingQueue</code> Implementations</h2>
<p>Java provides several implementations of the <code>BlockingQueue</code> interface, each suited for different use cases:</p>
<ul>
<li><strong><code>ArrayBlockingQueue</code></strong>: A bounded queue backed by an array. It&rsquo;s efficient but has a fixed capacity.</li>
<li><strong><code>LinkedBlockingQueue</code></strong>: An optionally bounded queue backed by linked nodes. It offers higher throughput than <code>ArrayBlockingQueue</code> but can consume more memory.</li>
<li><strong><code>PriorityBlockingQueue</code></strong>: An unbounded queue where elements are ordered based on their natural ordering or a custom <code>Comparator</code>.</li>
<li><strong><code>DelayQueue</code></strong>: An unbounded queue where elements can only be taken when their specified delay has expired.</li>
<li><strong><code>SynchronousQueue</code></strong>: A queue with no internal capacity. Each <code>put()</code> operation must wait for a corresponding <code>take()</code> operation, making it ideal for handoff scenarios.</li>
</ul>
<p>By choosing the right implementation, you can tailor the behavior of your concurrent application to your specific needs.</p>
]]></content>
        </item>
        
        <item>
            <title>Mastering Asynchronous Programming with Java&#39;s CompletableFuture</title>
            <link>https://aamernabi.github.io/posts/java-completable-future/</link>
            <pubDate>Mon, 27 Jul 2020 12:09:10 +0530</pubDate>
            
            <guid>https://aamernabi.github.io/posts/java-completable-future/</guid>
            <description>&lt;p&gt;Introduced in Java 8, &lt;code&gt;CompletableFuture&lt;/code&gt; is a powerful class for asynchronous programming. It extends the traditional &lt;code&gt;Future&lt;/code&gt; interface with a rich set of features for composing, combining, and handling asynchronous tasks, enabling you to write non-blocking, highly concurrent applications with ease.&lt;/p&gt;
&lt;h2 id=&#34;why-completablefuture&#34;&gt;Why &lt;code&gt;CompletableFuture&lt;/code&gt;?&lt;/h2&gt;
&lt;p&gt;Before &lt;code&gt;CompletableFuture&lt;/code&gt;, Java&amp;rsquo;s &lt;code&gt;Future&lt;/code&gt; was limited. You could start an asynchronous task, but you had to block your main thread using &lt;code&gt;get()&lt;/code&gt; to retrieve the result. This defeated the purpose of non-blocking code.&lt;/p&gt;</description>
            <content type="html"><![CDATA[<p>Introduced in Java 8, <code>CompletableFuture</code> is a powerful class for asynchronous programming. It extends the traditional <code>Future</code> interface with a rich set of features for composing, combining, and handling asynchronous tasks, enabling you to write non-blocking, highly concurrent applications with ease.</p>
<h2 id="why-completablefuture">Why <code>CompletableFuture</code>?</h2>
<p>Before <code>CompletableFuture</code>, Java&rsquo;s <code>Future</code> was limited. You could start an asynchronous task, but you had to block your main thread using <code>get()</code> to retrieve the result. This defeated the purpose of non-blocking code.</p>
<p><code>CompletableFuture</code> solves this by providing a <strong>non-blocking, callback-based approach</strong>. It allows you to chain tasks together, so that a subsequent task automatically executes when the previous one completes, without ever blocking your main thread.</p>
<h2 id="core-features-of-completablefuture">Core Features of <code>CompletableFuture</code></h2>
<ul>
<li><strong>Asynchronous Execution</strong>: Run tasks in the background without blocking the caller thread, typically using a <code>ForkJoinPool</code> or a custom <code>Executor</code>.</li>
<li><strong>Composability and Chaining</strong>: Chain multiple asynchronous operations together using methods like <code>thenApply()</code>, <code>thenAccept()</code>, and <code>thenCompose()</code>.</li>
<li><strong>Powerful Combination</strong>: Combine the results of multiple <code>CompletableFutures</code> using <code>thenCombine()</code>, <code>allOf()</code>, or <code>anyOf()</code>.</li>
<li><strong>Robust Exception Handling</strong>: Handle exceptions gracefully within the asynchronous pipeline using methods like <code>exceptionally()</code> and <code>handle()</code>.</li>
<li><strong>Explicit Completion</strong>: Programmatically complete a future with a result or an exception, giving you more control over its lifecycle.</li>
</ul>
<h2 id="key-methods-of-completablefuture">Key Methods of <code>CompletableFuture</code></h2>
<p>Here&rsquo;s a look at some of the most commonly used methods:</p>
<table>
  <thead>
      <tr>
          <th>Method</th>
          <th>Description</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td><code>supplyAsync(Supplier)</code></td>
          <td>Runs a task asynchronously that returns a result.</td>
      </tr>
      <tr>
          <td><code>runAsync(Runnable)</code></td>
          <td>Runs a task asynchronously that doesn&rsquo;t return a result.</td>
      </tr>
      <tr>
          <td><code>thenApply(Function)</code></td>
          <td>Transforms the result of a <code>CompletableFuture</code> when it completes.</td>
      </tr>
      <tr>
          <td><code>thenAccept(Consumer)</code></td>
          <td>Consumes the result of a <code>CompletableFuture</code> when it completes.</td>
      </tr>
      <tr>
          <td><code>thenRun(Runnable)</code></td>
          <td>Executes a <code>Runnable</code> after a <code>CompletableFuture</code> completes.</td>
      </tr>
      <tr>
          <td><code>thenCombine()</code></td>
          <td>Combines the results of two <code>CompletableFutures</code> when both are done.</td>
      </tr>
      <tr>
          <td><code>exceptionally(Function)</code></td>
          <td>Provides a fallback value in case of an exception.</td>
      </tr>
      <tr>
          <td><code>join()</code></td>
          <td>Waits for the computation to complete and returns the result (throws an unchecked exception).</td>
      </tr>
      <tr>
          <td><code>get()</code></td>
          <td>Similar to <code>join()</code>, but throws checked exceptions.</td>
      </tr>
  </tbody>
</table>
<h2 id="how-does-completablefuture-work">How Does <code>CompletableFuture</code> Work?</h2>
<ol>
<li><strong>Asynchronous Task Execution</strong>: When you call <code>supplyAsync()</code> or <code>runAsync()</code>, the task is submitted to a thread pool (by default, the <code>ForkJoinPool.commonPool()</code>). Your main thread is free to continue its work.</li>
<li><strong>Callback Chaining</strong>: You can attach callbacks using methods like <code>thenApply()</code> or <code>thenAccept()</code>. These callbacks are registered and will be executed only when the preceding task finishes.</li>
<li><strong>Result and Exception Handling</strong>: The <code>CompletableFuture</code> object holds the state of the computation (e.g., pending, completed with a result, or completed with an exception). When a task finishes, it triggers the execution of any dependent callbacks.</li>
<li><strong>Combining Futures</strong>: Methods like <code>allOf()</code> and <code>anyOf()</code> allow you to coordinate multiple asynchronous tasks, enabling you to proceed when all or any of them have completed.</li>
</ol>
<h2 id="practical-example">Practical Example</h2>
<p>Let&rsquo;s see <code>CompletableFuture</code> in action with a simple example:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#f92672">import</span> java.util.concurrent.CompletableFuture;
</span></span><span style="display:flex;"><span><span style="color:#f92672">import</span> java.util.concurrent.TimeUnit;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">CompletableFutureExample</span> {
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">main</span>(String<span style="color:#f92672">[]</span> args) {
</span></span><span style="display:flex;"><span>        CompletableFuture<span style="color:#f92672">&lt;</span>String<span style="color:#f92672">&gt;</span> future <span style="color:#f92672">=</span> CompletableFuture.<span style="color:#a6e22e">supplyAsync</span>(() <span style="color:#f92672">-&gt;</span> {
</span></span><span style="display:flex;"><span>            <span style="color:#75715e">// Simulate a long-running task</span>
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">try</span> {
</span></span><span style="display:flex;"><span>                TimeUnit.<span style="color:#a6e22e">SECONDS</span>.<span style="color:#a6e22e">sleep</span>(1);
</span></span><span style="display:flex;"><span>            } <span style="color:#66d9ef">catch</span> (InterruptedException e) {
</span></span><span style="display:flex;"><span>                <span style="color:#66d9ef">throw</span> <span style="color:#66d9ef">new</span> IllegalStateException(e);
</span></span><span style="display:flex;"><span>            }
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> <span style="color:#e6db74">&#34;Hello&#34;</span>;
</span></span><span style="display:flex;"><span>        }).<span style="color:#a6e22e">thenApply</span>(result <span style="color:#f92672">-&gt;</span> result <span style="color:#f92672">+</span> <span style="color:#e6db74">&#34; World!&#34;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Attach a callback to consume the final result</span>
</span></span><span style="display:flex;"><span>        future.<span style="color:#a6e22e">thenAccept</span>(result <span style="color:#f92672">-&gt;</span> {
</span></span><span style="display:flex;"><span>            System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(<span style="color:#e6db74">&#34;Result: &#34;</span> <span style="color:#f92672">+</span> result);
</span></span><span style="display:flex;"><span>            System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(<span style="color:#e6db74">&#34;This is executed in thread: &#34;</span> <span style="color:#f92672">+</span> Thread.<span style="color:#a6e22e">currentThread</span>().<span style="color:#a6e22e">getName</span>());
</span></span><span style="display:flex;"><span>        });
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(<span style="color:#e6db74">&#34;This is printed immediately from the main thread.&#34;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Wait for the future to complete to see the output</span>
</span></span><span style="display:flex;"><span>        future.<span style="color:#a6e22e">join</span>();
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>In this example:</p>
<ol>
<li><code>supplyAsync()</code> starts a background task.</li>
<li><code>thenApply()</code> chains another task to transform the result.</li>
<li><code>thenAccept()</code> registers a final callback to print the result.</li>
<li>The main thread prints its message immediately and then calls <code>join()</code> to wait for the asynchronous pipeline to finish before exiting.</li>
</ol>
<p>By leveraging <code>CompletableFuture</code>, you can build sophisticated, non-blocking, and highly efficient applications in Java.</p>
]]></content>
        </item>
        
        <item>
            <title>Understanding Java&#39;s hashCode() and equals() Contract</title>
            <link>https://aamernabi.github.io/posts/java-hashcode/</link>
            <pubDate>Sun, 26 Jul 2020 23:03:02 +0530</pubDate>
            
            <guid>https://aamernabi.github.io/posts/java-hashcode/</guid>
            <description>&lt;p&gt;In Java, the &lt;code&gt;hashCode()&lt;/code&gt; method, inherited from the &lt;code&gt;Object&lt;/code&gt; class, plays a crucial role in the efficient functioning of hash-based collections like &lt;code&gt;HashMap&lt;/code&gt;, &lt;code&gt;HashSet&lt;/code&gt;, and &lt;code&gt;Hashtable&lt;/code&gt;. It generates an integer hash code value for an object, which is used to determine the &amp;ldquo;bucket&amp;rdquo; where the object should be stored.&lt;/p&gt;
&lt;h2 id=&#34;the-hashcode-and-equals-contract&#34;&gt;The &lt;code&gt;hashCode()&lt;/code&gt; and &lt;code&gt;equals()&lt;/code&gt; Contract&lt;/h2&gt;
&lt;p&gt;The most important concept to understand is the contract between &lt;code&gt;hashCode()&lt;/code&gt; and &lt;code&gt;equals()&lt;/code&gt;:&lt;/p&gt;
&lt;blockquote&gt;
&lt;ol&gt;
&lt;li&gt;If two objects are equal according to the &lt;code&gt;equals(Object)&lt;/code&gt; method, then calling the &lt;code&gt;hashCode()&lt;/code&gt; method on each of the two objects must produce the same integer result.&lt;/li&gt;
&lt;li&gt;It is &lt;em&gt;not&lt;/em&gt; required that if two objects are unequal according to the &lt;code&gt;equals(Object)&lt;/code&gt; method, then calling the &lt;code&gt;hashCode()&lt;/code&gt; method on each of the two objects must produce distinct integer results. However, producing distinct hash codes for unequal objects may improve the performance of hash tables.&lt;/li&gt;
&lt;/ol&gt;&lt;/blockquote&gt;
&lt;p&gt;In simple terms: &lt;strong&gt;equal objects must have equal hash codes.&lt;/strong&gt;&lt;/p&gt;</description>
            <content type="html"><![CDATA[<p>In Java, the <code>hashCode()</code> method, inherited from the <code>Object</code> class, plays a crucial role in the efficient functioning of hash-based collections like <code>HashMap</code>, <code>HashSet</code>, and <code>Hashtable</code>. It generates an integer hash code value for an object, which is used to determine the &ldquo;bucket&rdquo; where the object should be stored.</p>
<h2 id="the-hashcode-and-equals-contract">The <code>hashCode()</code> and <code>equals()</code> Contract</h2>
<p>The most important concept to understand is the contract between <code>hashCode()</code> and <code>equals()</code>:</p>
<blockquote>
<ol>
<li>If two objects are equal according to the <code>equals(Object)</code> method, then calling the <code>hashCode()</code> method on each of the two objects must produce the same integer result.</li>
<li>It is <em>not</em> required that if two objects are unequal according to the <code>equals(Object)</code> method, then calling the <code>hashCode()</code> method on each of the two objects must produce distinct integer results. However, producing distinct hash codes for unequal objects may improve the performance of hash tables.</li>
</ol></blockquote>
<p>In simple terms: <strong>equal objects must have equal hash codes.</strong></p>
<p>If you override the <code>equals()</code> method, you <strong>must</strong> also override the <code>hashCode()</code> method to maintain this contract.</p>
<h2 id="why-is-this-contract-so-important">Why is This Contract So Important?</h2>
<p>Hash-based collections use an object&rsquo;s hash code to quickly locate it. Here&rsquo;s a simplified view of how <code>HashMap.put(key, value)</code> works:</p>
<ol>
<li>It calculates the <code>key</code>&rsquo;s hash code.</li>
<li>It uses this hash code to find a bucket (an index in an internal array).</li>
<li>If the bucket is empty, it stores the key-value pair there.</li>
<li>If the bucket is not empty (a hash collision), it iterates through the existing entries in that bucket and uses the <code>equals()</code> method to check if the key already exists.</li>
</ol>
<p>If you break the contract, these collections will behave incorrectly.</p>
<h3 id="example-breaking-the-contract">Example: Breaking the Contract</h3>
<p>Let&rsquo;s see what happens when we override <code>equals()</code> but not <code>hashCode()</code>.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#f92672">import</span> java.util.HashMap;
</span></span><span style="display:flex;"><span><span style="color:#f92672">import</span> java.util.Map;
</span></span><span style="display:flex;"><span><span style="color:#f92672">import</span> java.util.Objects;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Product</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> String id;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">Product</span>(String id) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">id</span> <span style="color:#f92672">=</span> id;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">@Override</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">boolean</span> <span style="color:#a6e22e">equals</span>(Object o) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (<span style="color:#66d9ef">this</span> <span style="color:#f92672">==</span> o) <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">true</span>;
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (o <span style="color:#f92672">==</span> <span style="color:#66d9ef">null</span> <span style="color:#f92672">||</span> getClass() <span style="color:#f92672">!=</span> o.<span style="color:#a6e22e">getClass</span>()) <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">false</span>;
</span></span><span style="display:flex;"><span>        Product product <span style="color:#f92672">=</span> (Product) o;
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> Objects.<span style="color:#a6e22e">equals</span>(id, product.<span style="color:#a6e22e">id</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// hashCode() is NOT overridden</span>
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">BrokenContractExample</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">main</span>(String<span style="color:#f92672">[]</span> args) {
</span></span><span style="display:flex;"><span>        Map<span style="color:#f92672">&lt;</span>Product, String<span style="color:#f92672">&gt;</span> map <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> HashMap<span style="color:#f92672">&lt;&gt;</span>();
</span></span><span style="display:flex;"><span>        map.<span style="color:#a6e22e">put</span>(<span style="color:#66d9ef">new</span> Product(<span style="color:#e6db74">&#34;a&#34;</span>), <span style="color:#e6db74">&#34;Apple&#34;</span>);
</span></span><span style="display:flex;"><span>        map.<span style="color:#a6e22e">put</span>(<span style="color:#66d9ef">new</span> Product(<span style="color:#e6db74">&#34;a&#34;</span>), <span style="color:#e6db74">&#34;Avocado&#34;</span>); <span style="color:#75715e">// Should replace &#34;Apple&#34;</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// The map size will be 2, which is incorrect!</span>
</span></span><span style="display:flex;"><span>        System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(<span style="color:#e6db74">&#34;Map size: &#34;</span> <span style="color:#f92672">+</span> map.<span style="color:#a6e22e">size</span>());
</span></span><span style="display:flex;"><span>        System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(map);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p><strong>What went wrong?</strong></p>
<ul>
<li>We defined <code>equals()</code> to consider two <code>Product</code> objects with the same <code>id</code> as equal.</li>
<li>However, since we didn&rsquo;t override <code>hashCode()</code>, each <code>new Product(&quot;a&quot;)</code> gets a different hash code from the default <code>Object.hashCode()</code> implementation (which is based on memory address).</li>
<li>The <code>HashMap</code> calculates two different hash codes, places the objects in two different buckets, and never even calls the <code>equals()</code> method. The result is a map with duplicate logical keys.</li>
</ul>
<h2 id="how-to-correctly-implement-hashcode">How to Correctly Implement <code>hashCode()</code></h2>
<p>To fix this, we must implement <code>hashCode()</code> based on the same fields used in the <code>equals()</code> method. The easiest way is to use the <code>Objects.hash()</code> utility method.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#f92672">import</span> java.util.HashMap;
</span></span><span style="display:flex;"><span><span style="color:#f92672">import</span> java.util.Map;
</span></span><span style="display:flex;"><span><span style="color:#f92672">import</span> java.util.Objects;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">CorrectProduct</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> String id;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">CorrectProduct</span>(String id) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">id</span> <span style="color:#f92672">=</span> id;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">@Override</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">boolean</span> <span style="color:#a6e22e">equals</span>(Object o) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (<span style="color:#66d9ef">this</span> <span style="color:#f92672">==</span> o) <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">true</span>;
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (o <span style="color:#f92672">==</span> <span style="color:#66d9ef">null</span> <span style="color:#f92672">||</span> getClass() <span style="color:#f92672">!=</span> o.<span style="color:#a6e22e">getClass</span>()) <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">false</span>;
</span></span><span style="display:flex;"><span>        CorrectProduct that <span style="color:#f92672">=</span> (CorrectProduct) o;
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> Objects.<span style="color:#a6e22e">equals</span>(id, that.<span style="color:#a6e22e">id</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">@Override</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">int</span> <span style="color:#a6e22e">hashCode</span>() {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Use the same field(s) as in equals()</span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> Objects.<span style="color:#a6e22e">hash</span>(id);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">CorrectContractExample</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">main</span>(String<span style="color:#f92672">[]</span> args) {
</span></span><span style="display:flex;"><span>        Map<span style="color:#f92672">&lt;</span>CorrectProduct, String<span style="color:#f92672">&gt;</span> map <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> HashMap<span style="color:#f92672">&lt;&gt;</span>();
</span></span><span style="display:flex;"><span>        map.<span style="color:#a6e22e">put</span>(<span style="color:#66d9ef">new</span> CorrectProduct(<span style="color:#e6db74">&#34;a&#34;</span>), <span style="color:#e6db74">&#34;Apple&#34;</span>);
</span></span><span style="display:flex;"><span>        map.<span style="color:#a6e22e">put</span>(<span style="color:#66d9ef">new</span> CorrectProduct(<span style="color:#e6db74">&#34;a&#34;</span>), <span style="color:#e6db74">&#34;Avocado&#34;</span>); <span style="color:#75715e">// Correctly replaces &#34;Apple&#34;</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// The map size will be 1, which is correct.</span>
</span></span><span style="display:flex;"><span>        System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(<span style="color:#e6db74">&#34;Map size: &#34;</span> <span style="color:#f92672">+</span> map.<span style="color:#a6e22e">size</span>());
</span></span><span style="display:flex;"><span>        System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(map);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>By correctly implementing both <code>equals()</code> and <code>hashCode()</code>, we ensure that hash-based collections work as expected, providing both correctness and performance.</p>
]]></content>
        </item>
        
        <item>
            <title>Understanding Fail-Fast vs. Fail-Safe Iterators in Java</title>
            <link>https://aamernabi.github.io/posts/java-fail-fast-vs-fail-safe-iterators/</link>
            <pubDate>Mon, 20 Jul 2020 15:44:00 +0530</pubDate>
            
            <guid>https://aamernabi.github.io/posts/java-fail-fast-vs-fail-safe-iterators/</guid>
            <description>&lt;p&gt;When working with collections in Java, you&amp;rsquo;ll often use iterators to traverse through their elements. However, not all iterators are created equal. Two common types you&amp;rsquo;ll encounter are &lt;strong&gt;fail-fast&lt;/strong&gt; and &lt;strong&gt;fail-safe&lt;/strong&gt; iterators. Understanding the difference between them is crucial for writing robust and error-free code.&lt;/p&gt;
&lt;h2 id=&#34;fail-fast-iterators&#34;&gt;Fail-Fast Iterators&lt;/h2&gt;
&lt;p&gt;Fail-fast iterators immediately throw a &lt;code&gt;ConcurrentModificationException&lt;/code&gt; if the collection is structurally modified (i.e., elements are added or removed) at any time after the iterator is created, except through the iterator&amp;rsquo;s own &lt;code&gt;remove()&lt;/code&gt; method.&lt;/p&gt;</description>
            <content type="html"><![CDATA[<p>When working with collections in Java, you&rsquo;ll often use iterators to traverse through their elements. However, not all iterators are created equal. Two common types you&rsquo;ll encounter are <strong>fail-fast</strong> and <strong>fail-safe</strong> iterators. Understanding the difference between them is crucial for writing robust and error-free code.</p>
<h2 id="fail-fast-iterators">Fail-Fast Iterators</h2>
<p>Fail-fast iterators immediately throw a <code>ConcurrentModificationException</code> if the collection is structurally modified (i.e., elements are added or removed) at any time after the iterator is created, except through the iterator&rsquo;s own <code>remove()</code> method.</p>
<h3 id="how-they-work">How They Work</h3>
<p>Fail-fast iterators operate directly on the collection itself. They keep track of the number of modifications made to the collection using an internal flag (like <code>modCount</code>). When you create an iterator, it saves the initial <code>modCount</code>. With each iteration (<code>next()</code> call), it checks if the current <code>modCount</code> has changed. If it has, the iterator knows that the collection has been modified concurrently and throws a <code>ConcurrentModificationException</code>.</p>
<p>This mechanism helps to prevent unexpected behavior and data corruption by alerting you to concurrent modification issues early on.</p>
<p>Common collections that use fail-fast iterators include <code>ArrayList</code>, <code>HashMap</code>, and <code>HashSet</code>.</p>
<h3 id="code-example">Code Example</h3>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#f92672">import</span> java.util.ArrayList;
</span></span><span style="display:flex;"><span><span style="color:#f92672">import</span> java.util.Arrays;
</span></span><span style="display:flex;"><span><span style="color:#f92672">import</span> java.util.Iterator;
</span></span><span style="display:flex;"><span><span style="color:#f92672">import</span> java.util.List;
</span></span><span style="display:flex;"><span><span style="color:#f92672">import</span> java.util.ConcurrentModificationException;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">FailFastExample</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">main</span>(String<span style="color:#f92672">[]</span> args) {
</span></span><span style="display:flex;"><span>        List<span style="color:#f92672">&lt;</span>String<span style="color:#f92672">&gt;</span> list <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> ArrayList<span style="color:#f92672">&lt;&gt;</span>(Arrays.<span style="color:#a6e22e">asList</span>(<span style="color:#e6db74">&#34;A&#34;</span>, <span style="color:#e6db74">&#34;B&#34;</span>, <span style="color:#e6db74">&#34;C&#34;</span>));
</span></span><span style="display:flex;"><span>        Iterator<span style="color:#f92672">&lt;</span>String<span style="color:#f92672">&gt;</span> iterator <span style="color:#f92672">=</span> list.<span style="color:#a6e22e">iterator</span>();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">while</span> (iterator.<span style="color:#a6e22e">hasNext</span>()) {
</span></span><span style="display:flex;"><span>            String element <span style="color:#f92672">=</span> iterator.<span style="color:#a6e22e">next</span>();
</span></span><span style="display:flex;"><span>            System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(<span style="color:#e6db74">&#34;Processing: &#34;</span> <span style="color:#f92672">+</span> element);
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">try</span> {
</span></span><span style="display:flex;"><span>                <span style="color:#75715e">// This will throw ConcurrentModificationException</span>
</span></span><span style="display:flex;"><span>                list.<span style="color:#a6e22e">add</span>(<span style="color:#e6db74">&#34;D&#34;</span>); 
</span></span><span style="display:flex;"><span>            } <span style="color:#66d9ef">catch</span> (ConcurrentModificationException e) {
</span></span><span style="display:flex;"><span>                System.<span style="color:#a6e22e">err</span>.<span style="color:#a6e22e">println</span>(<span style="color:#e6db74">&#34;Caught a ConcurrentModificationException!&#34;</span>);
</span></span><span style="display:flex;"><span>                e.<span style="color:#a6e22e">printStackTrace</span>();
</span></span><span style="display:flex;"><span>                <span style="color:#66d9ef">break</span>; 
</span></span><span style="display:flex;"><span>            }
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>In this example, <code>list.add(&quot;D&quot;)</code> modifies the list while the iterator is active, causing a <code>ConcurrentModificationException</code> to be thrown.</p>
<h2 id="fail-safe-iterators">Fail-Safe Iterators</h2>
<p>In contrast, fail-safe iterators (also known as non-fast-fail iterators) do <strong>not</strong> throw a <code>ConcurrentModificationException</code> if the collection is modified while being iterated.</p>
<h3 id="how-they-work-1">How They Work</h3>
<p>Fail-safe iterators work on a clone or a snapshot of the underlying collection. This means that any modifications made to the original collection do not affect the iterator. The iterator continues to traverse the snapshot, which remains unchanged. This approach ensures that the iteration can complete without errors, but it also means that the iterator might not reflect the most up-to-date state of the collection.</p>
<p>Collections that use fail-safe iterators are typically found in the <code>java.util.concurrent</code> package, such as <code>CopyOnWriteArrayList</code> and <code>ConcurrentHashMap</code>.</p>
<h3 id="code-example-1">Code Example</h3>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#f92672">import</span> java.util.Iterator;
</span></span><span style="display:flex;"><span><span style="color:#f92672">import</span> java.util.concurrent.CopyOnWriteArrayList;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">FailSafeExample</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">main</span>(String<span style="color:#f92672">[]</span> args) {
</span></span><span style="display:flex;"><span>        CopyOnWriteArrayList<span style="color:#f92672">&lt;</span>String<span style="color:#f92672">&gt;</span> list <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> CopyOnWriteArrayList<span style="color:#f92672">&lt;&gt;</span>(<span style="color:#66d9ef">new</span> String<span style="color:#f92672">[]</span>{<span style="color:#e6db74">&#34;A&#34;</span>, <span style="color:#e6db74">&#34;B&#34;</span>, <span style="color:#e6db74">&#34;C&#34;</span>});
</span></span><span style="display:flex;"><span>        Iterator<span style="color:#f92672">&lt;</span>String<span style="color:#f92672">&gt;</span> iterator <span style="color:#f92672">=</span> list.<span style="color:#a6e22e">iterator</span>();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">while</span> (iterator.<span style="color:#a6e22e">hasNext</span>()) {
</span></span><span style="display:flex;"><span>            String element <span style="color:#f92672">=</span> iterator.<span style="color:#a6e22e">next</span>();
</span></span><span style="display:flex;"><span>            System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(<span style="color:#e6db74">&#34;Processing: &#34;</span> <span style="color:#f92672">+</span> element);
</span></span><span style="display:flex;"><span>            
</span></span><span style="display:flex;"><span>            <span style="color:#75715e">// This modification will not be reflected in the iterator</span>
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">if</span> (element.<span style="color:#a6e22e">equals</span>(<span style="color:#e6db74">&#34;B&#34;</span>)) {
</span></span><span style="display:flex;"><span>                list.<span style="color:#a6e22e">add</span>(<span style="color:#e6db74">&#34;D&#34;</span>);
</span></span><span style="display:flex;"><span>            }
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>        
</span></span><span style="display:flex;"><span>        System.<span style="color:#a6e22e">out</span>.<span style="color:#a6e22e">println</span>(<span style="color:#e6db74">&#34;Final list: &#34;</span> <span style="color:#f92672">+</span> list);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>In this case, even though we add &ldquo;D&rdquo; to the list, the iterator doesn&rsquo;t throw an exception. The output will show that the iterator processed the original elements (&ldquo;A&rdquo;, &ldquo;B&rdquo;, &ldquo;C&rdquo;), and the final list contains &ldquo;D&rdquo;.</p>
<h2 id="key-differences-fail-fast-vs-fail-safe">Key Differences: Fail-Fast vs. Fail-Safe</h2>
<table>
  <thead>
      <tr>
          <th>Feature</th>
          <th>Fail-Fast Iterator</th>
          <th>Fail-Safe Iterator</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td><strong>Exception Handling</strong></td>
          <td>Throws <code>ConcurrentModificationException</code></td>
          <td>Does not throw any exception</td>
      </tr>
      <tr>
          <td><strong>Underlying Data</strong></td>
          <td>Operates on the original collection</td>
          <td>Operates on a clone or snapshot of the collection</td>
      </tr>
      <tr>
          <td><strong>Consistency</strong></td>
          <td>Reflects the current state until modification</td>
          <td>May not reflect the latest state of the collection</td>
      </tr>
      <tr>
          <td><strong>Performance</strong></td>
          <td>Generally faster as it doesn&rsquo;t create a copy</td>
          <td>Slower due to the overhead of creating a snapshot</td>
      </tr>
      <tr>
          <td><strong>Examples</strong></td>
          <td><code>ArrayList</code>, <code>HashMap</code>, <code>HashSet</code></td>
          <td><code>CopyOnWriteArrayList</code>, <code>ConcurrentHashMap</code></td>
      </tr>
  </tbody>
</table>
<h2 id="conclusion">Conclusion</h2>
<p>Choosing between fail-fast and fail-safe iterators depends on your specific needs.</p>
<ul>
<li>Use <strong>fail-fast</strong> iterators when you need to be immediately aware of concurrent modifications, which is typical in single-threaded environments or when you can control modifications.</li>
<li>Opt for <strong>fail-safe</strong> iterators in multi-threaded environments where you need to ensure that iterations can proceed without interruption, even if the collection is being modified by other threads.</li>
</ul>
<p>By understanding these differences, you can write more reliable and predictable Java applications.</p>
]]></content>
        </item>
        
    </channel>
</rss>
