<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sandeep Rai on Medium]]></title>
        <description><![CDATA[Stories by Sandeep Rai on Medium]]></description>
        <link>https://medium.com/@sandeep-rai?source=rss-806d72b9e281------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*bKnurgRwFMibWN0JbffgEg.jpeg</url>
            <title>Stories by Sandeep Rai on Medium</title>
            <link>https://medium.com/@sandeep-rai?source=rss-806d72b9e281------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 20:46:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sandeep-rai/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[ConcurrentHashMap, Step by Step: How Java Makes HashMap Thread-Safe Without One Big Lock (Part 2)]]></title>
            <link>https://sandeep-rai.medium.com/concurrenthashmap-step-by-step-how-java-makes-hashmap-thread-safe-without-one-big-lock-part-2-5b60c99e4a64?source=rss-806d72b9e281------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b60c99e4a64</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[concurrenthashmap]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Sandeep Rai]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 12:57:25 GMT</pubDate>
            <atom:updated>2026-10-24T15:59:54.581Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/@sandeep-rai/five-steps-to-actually-understanding-hashmap-in-java-not-just-memorizing-it-9dd51b0c57a3">Part 1</a> built the full mental model of plain HashMap — bucket array, chaining, treeification, resizing, and the power-of-two bitmask trick that ties it together. None of that goes away here. ConcurrentHashMap uses the exact same bucket array, the exact same Node chains, the exact same bit-split resize logic — it just adds coordination on top, scoped as narrowly as possible. If Step 1 here feels unfamiliar, it&#39;s worth a quick re-read of Part 1 first; everything below assumes that structure is solid.</p><p>Same rule as last time: five steps, in order, each one only makes sense once the previous one is settled.</p><h3>Step 1: Why is plain HashMap unsafe with multiple threads?</h3><p>Picture two threads, both calling put() at the exact same moment, and both landing in the <strong>same empty bucket</strong> — say, bucket 5.</p><p>Here’s roughly what put() does: check if the bucket is empty → if so, create a new Node and write it in. Two threads can both check bucket 5, both see it&#39;s empty (neither has written yet), both create their own Node, and both write. Whichever write happens <em>second</em> simply overwrites the first — silently. No exception, no error. One thread&#39;s insert just vanishes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J0UAjKf2LIMA_AC94hMkhw.png" /></figure><p>This is called a <strong>lost update</strong>, and it’s the simplest failure mode. It gets worse during a <strong>resize</strong>: in Java 7’s implementation, two threads resizing concurrently could corrupt a bucket’s chain into a <em>cycle</em> — pointing back on itself — so a later get() on that bucket spins forever. (Java 8 changed the resize algorithm, so that specific bug is gone, but concurrent writes still aren&#39;t safe without help.)</p><p><strong>The core issue:</strong> every operation from <a href="https://medium.com/@sandeep-rai/five-steps-to-actually-understanding-hashmap-in-java-not-just-memorizing-it-9dd51b0c57a3">Part 1</a> — checking a bucket, walking a chain, writing a Node, splitting during resize — assumes it&#39;s the <em>only</em> thing touching the table at that instant. Multiple threads break that assumption, and plain HashMap has no mechanism to detect or prevent it.</p><h3>Step 2: The naive fix — one big lock</h3><p>The simplest possible fix: wrap the entire map behind a single lock. This is literally what Hashtable and Collections.synchronizedMap() do — every method synchronized on the same one lock object.</p><p><strong>Why it’s safe:</strong> only one thread can hold the lock at a time, so Step 1’s race is gone entirely — no two threads can ever simultaneously check-and-write anything, because no two threads can be inside any method at once.</p><p><strong>Why it’s a bad solution:</strong> think of 16 Kafka consumer threads writing to completely unrelated buckets — bucket 2, bucket 9, bucket 14, zero overlap. A single map-wide lock still forces them to run one at a time. Thread 2, targeting bucket 9, waits for Thread 1, which is busy with bucket 2 — a part of the map Thread 2 doesn’t even care about.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BgLfUZICnes7-2PtftglQw.png" /></figure><p><strong>The insight this exposes:</strong> the lock is far coarser than the actual conflict. Two threads only genuinely conflict if they touch the <em>same</em> bucket. A map-wide lock treats “any two threads touching the map at all” as a conflict — a massive overreaction that serializes work which could safely run in parallel. Even reads suffer, despite not modifying anything.</p><h3>Step 3: Locking at the bucket level — without a separate lock array</h3><p>The obvious next idea: 16 separate lock objects, one per bucket. Already a big improvement. But ConcurrentHashMap does something cleverer — it doesn&#39;t allocate a separate lock array at all. It reuses something already sitting right there: <strong>the bucket&#39;s own first </strong><strong>Node</strong>, as the lock itself.</p><pre>synchronized (firstNodeInBucket) {<br>    // safe to modify this bucket&#39;s chain<br>}</pre><p>Every object in Java can act as a monitor lock via synchronized — nothing special here, just applied deliberately. A thread touching bucket 5 synchronizes on bucket 5&#39;s head node. A thread touching bucket 9 synchronizes on bucket 9&#39;s head node — a different object entirely. They never contend, because they&#39;re never synchronizing on the same thing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nsH3sP8pBh42U4ASIM2R0Q.png" /></figure><p><strong>Why this beats a dedicated lock array:</strong> zero extra memory for lock objects, and it scales for free as the table resizes — new buckets’ head nodes just <em>are</em> their own locks, once they have an entry.</p><p><strong>The gap this leaves:</strong> this only works for buckets that already contain a Node. An empty bucket has nothing to synchronize on. That&#39;s Step 4.</p><h3>Step 4: The empty-bucket case (CAS) — and why reads never lock at all</h3><h3>Inserting into an empty bucket: CAS, not a lock</h3><p>CAS — <strong>compare-and-swap</strong> — is a single CPU instruction (hardware-level, exposed to Java via sun.misc.Unsafe historically, and VarHandle in modern Java; the public-facing wrapper classes are java.util.concurrent.atomic.*, like AtomicInteger). It does this atomically, as one indivisible step: <em>&quot;if this memory location still holds the value I expect, write my new value — otherwise tell me it failed.&quot;</em></p><pre>// &quot;if table[5] is still null, set it to newNode — atomically&quot;<br>casTabAt(table, 5, null, newNode)</pre><p>Two threads can attempt this at the exact same instant; the CPU guarantees only one succeeds. The other’s CAS simply fails, and that thread retries — falling into Step 3’s locked path if a real node now exists.</p><p><strong>Why CAS can’t cover the collision case too</strong> — the check stops being simple. Inserting into an <em>occupied</em> bucket is read-decide-write: walk the chain, compare keys via equals() (is this actually an update, not an insert?), then append if no match. Between the read and the write, another thread could&#39;ve modified the same chain — a single CAS on one pointer can&#39;t verify &quot;the whole chain I traversed is still exactly as I saw it.&quot; That&#39;s a multi-step operation; CAS only protects one memory word. synchronized handles the multi-step case cleanly instead — and since collisions are supposed to be rare by design, the lock is held only briefly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QiMZN64lbKmOwApKp_NXhQ.png" /></figure><h3>Why get() never blocks, on any bucket</h3><p>The val and next fields inside each Node are volatile — guaranteeing that a write by one thread is immediately visible to every other thread, no stale cached copies. Because of that, get() can walk a bucket&#39;s chain with zero locking and still see a consistent view of whatever&#39;s been written so far.</p><p><strong>What </strong><strong>volatile does <em>not</em> give you:</strong> it doesn&#39;t make multi-step operations atomic — it guarantees each individual read/write is visible, not that &quot;check-then-act&quot; is safe. That&#39;s exactly why put() still needs CAS or synchronized: writing is multi-step, reading a single pointer chain isn&#39;t.</p><p><strong>One precise term worth knowing:</strong> ConcurrentHashMap reads are <strong>&quot;weakly consistent.&quot;</strong> get() is guaranteed to never see a torn or half-written state — because a thread fully builds a new Node before publishing it with one volatile write — but it is <em>not</em> guaranteed to reflect a write that&#39;s happening at the exact same instant. It&#39;ll see the chain either fully without the new node, or fully with it — never something in between.</p><p><strong>Treeified buckets (≥ 8 entries) follow the same split:</strong> writes synchronize on the TreeBin (the tree&#39;s wrapper object) instead of a plain Node, since rebalancing touches multiple nodes at once — the same &quot;multi-step, needs a lock&quot; reasoning as regular collisions. But TreeBin nodes also maintain a plain linked-list structure <em>alongside</em> the tree, specifically so get() can walk that list instead of the tree — meaning reads on a treeified bucket still never need a lock, even while a rebalance is actively happening.</p><h3>Step 5: Multiple threads cooperating on a resize</h3><p>This is the most impressive piece — instead of one thread blocking everyone while it resizes (which would undo all the parallelism from Steps 3–4), multiple threads <strong>actively help the resize happen together</strong>.</p><h3>Starting the resize: only one thread wins</h3><p>There’s a shared control field, sizeCtl. Normally it holds the next resize threshold (capacity × 0.75). When multiple threads cross that threshold at once, each attempts a <strong>CAS on </strong><strong>sizeCtl itself</strong> — &quot;is this still the old threshold value? If so, swap it to a special in-progress marker.&quot; Only one thread&#39;s CAS succeeds; that thread allocates the new, doubled table. Every other thread&#39;s CAS fails, notices the in-progress marker, and joins as a <strong>helper</strong> instead of starting a redundant second resize.</p><h3>Claiming and moving buckets</h3><p>Threads claim ranges of old-table bucket indices via CAS on a shared “next unclaimed index” counter — no two threads claim the same bucket. For each bucket it claims, a thread does exactly the bit-split logic from Part 1’s Step 5: an entry at old index i goes to new index i or i + oldCapacity, decided by one bit. Same math — just distributed across threads instead of done by one.</p><h3>The ForwardingNode: one marker, two jobs</h3><p>While a bucket is being transferred, its old slot gets replaced with a <strong>ForwardingNode</strong> — a placeholder pointing to the new table. Critically, the new table is <strong>fully populated for that bucket before</strong> the ForwardingNode is published — data first, forwarding signal second, guaranteed by the Java Memory Model&#39;s happens-before ordering. So any thread that observes a ForwardingNode is guaranteed the corresponding data already exists in the new table — never a half-moved state.</p><p>That one marker does two jobs at once:</p><ul><li><strong>A </strong><strong>get() that hits it</strong> follows it straight to the new table instead — reads stay correct and lock-free even mid-resize.</li><li><strong>A </strong><strong>put() that hits it</strong> treats it as a signal to go help — claim some unclaimed buckets — rather than writing into a bucket that&#39;s actively being moved.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r9c9bBxCu3MhpT6agLQ8gA.png" /></figure><h3>This is a reusable pattern, not just a HashMap trick</h3><p>Worth pulling out explicitly: <strong>incremental, cooperative resizing — claim a chunk via CAS, do the work, leave a forwarding marker for stragglers — is a general pattern for any shared data structure that needs to grow while staying live under concurrent access</strong>, not something specific to hashing. The same shape shows up in concurrent queues, skip lists, and other lock-minimal concurrent structures: avoid a single stop-the-world transition by (1) letting the structure exist in two states briefly, (2) using CAS to let exactly one party initiate the transition, (3) letting anyone else who shows up help finish it instead of blocking on it, and (4) leaving a marker so in-flight readers and writers get redirected automatically rather than needing to poll or check a flag. If you’re ever designing your own shared structure that needs to grow — a custom cache, a connection pool, a sharded counter — this is the shape to reach for before reaching for a global lock.</p><h3>The full system, in one picture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*anW5e8iiuby7xFH1CFw_fA.png" /></figure><p>Hashing still decides where an entry starts (identical to Part 1). What’s new is that <em>getting there safely</em> now depends on bucket state — CAS for the lock-free fast path, a lock scoped to one bucket for the collision case — while reads never pay for any of it, and growth is something the whole system cooperates on instead of something one thread does while everyone else waits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*am8KaE0SnHh992hLAGt2Xw.png" /></figure><h3>Test yourself</h3><p>Try answering each before reading the line below it — this is close to how it actually plays out under interview pressure.</p><p><strong>1. Two threads call </strong><strong>put() with keys hashing to different buckets. Do they block each other?</strong> No — but <em>why</em> depends on bucket state. If both buckets are empty, each insert is a lock-free CAS. If both already have entries, each synchronizes on its own bucket&#39;s head node — different lock objects, no contention either way.</p><p><strong>2. Thread A is mid-</strong><strong>put() on a bucket with 3 entries. Thread B calls </strong><strong>get() on a different key in that same bucket. Does B block?</strong> No. Reads never lock — val and next are volatile, so get() sees a coherent view (old or new) without ever waiting on A&#39;s lock.</p><p><strong>3. A bucket has treeified (≥ 8 entries). A new key hashes into it. CAS, </strong><strong>synchronized, or something else?</strong> synchronized — on the TreeBin, not a plain node. Rebalancing touches multiple nodes, which CAS can&#39;t cover atomically. Reads still skip the lock, because TreeBin keeps a plain linked list alongside the tree purely so get() has something lock-free to walk.</p><p><strong>4. A resize is moving bucket 5 to the new table. A </strong><strong>get() arrives for a key in bucket 5 at that exact moment. What does it see?</strong> Either the old chain (if the transfer for bucket 5 hasn&#39;t published a ForwardingNode yet — old data is still fully valid) or a ForwardingNode it follows to the new table (if the transfer already finished — new data is guaranteed already there). Never a gap between the two.</p><p><strong>5. Could two threads both decide to start a resize independently?</strong> No — both would attempt a CAS on the shared sizeCtl field; only one succeeds and becomes the resizer. The other detects the field already changed and joins as a helper instead.</p><p><strong>6. </strong><strong>map.put(null, &quot;value&quot;) — what happens?</strong> Throws NullPointerException. Unlike plain HashMap (which allows one null key via a hardcoded hash of 0), ConcurrentHashMap disallows null keys <em>and</em> values entirely — because in a concurrent context, get() returning null would be permanently ambiguous between &quot;never had a value,&quot; &quot;has a null value,&quot; and &quot;had a value, but another thread removed it a moment ago.&quot; There&#39;s no race-free way to tell those apart from outside, so null is excluded by design.</p><p><strong>7. Does iterating a </strong><strong>ConcurrentHashMap while another thread inserts throw </strong><strong>ConcurrentModificationException?</strong> No — the iterator is <strong>weakly consistent</strong>, not fail-fast like HashMap&#39;s. It won&#39;t throw, won&#39;t return a duplicate, and reflects <em>some</em> reasonably coherent state — but it makes no guarantee about whether a concurrent insert will or won&#39;t show up during your iteration. Never write code that depends on either outcome.</p><p><strong>8. Does a </strong><strong>compute()/</strong><strong>merge() lambda run inside the bucket lock, or outside it?</strong> Entirely inside — read, transform, and write all happen while the lock is held. This means the lambda must be fast and must never call back into the same map (nesting a put() or compute() on a different key, from inside one, risks deadlock if another thread does the reverse nesting at the same time).</p><p>Between <a href="https://medium.com/@sandeep-rai/five-steps-to-actually-understanding-hashmap-in-java-not-just-memorizing-it-9dd51b0c57a3">Part 1</a> and this post, that’s the complete arc: how a single-threaded HashMap is structured, and exactly what has to change — and what deliberately doesn&#39;t — to make the same structure safe under real concurrent load.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b60c99e4a64" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Five Steps to Actually Understanding HashMap in Java (Not Just Memorizing It)]]></title>
            <link>https://sandeep-rai.medium.com/five-steps-to-actually-understanding-hashmap-in-java-not-just-memorizing-it-9dd51b0c57a3?source=rss-806d72b9e281------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dd51b0c57a3</guid>
            <category><![CDATA[hashmap]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Sandeep Rai]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 12:52:26 GMT</pubDate>
            <atom:updated>2026-10-24T16:16:29.740Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve interviewed for a Java backend role, you’ve heard some version of: <em>“Tell me how HashMap works internally.”</em> Most answers are a list of memorized facts — “default capacity 16,” “load factor 0.75,” “treeifies at 8” — recited without any sense of why those numbers exist or how they connect.</p><p>This post builds the whole picture from one single idea, one step at a time. Each step only makes sense once the previous one is solid — skip ahead and the later steps feel like arbitrary trivia again. Read them in order.</p><h3>Step 1: What problem is a HashMap even solving?</h3><p>Imagine storing data like a phone book: &quot;Alice&quot; → &quot;9876543210&quot;. The simplest approach is a plain list — keep appending (name, number) pairs.</p><p><strong>The problem:</strong> finding Alice’s number means scanning the list one entry at a time until you find a match. With a million entries, that’s up to a million checks.</p><p><strong>The idea behind HashMap:</strong> instead of scanning, what if you could jump <em>directly</em> to roughly the right spot?</p><p>That’s what a <strong>hash</strong> gives you. A hash function takes a key and turns it into a number — fast, and the same input always produces the same output. &quot;Alice&quot; might hash to 93. If you have an array of 8 slots (<strong>buckets</strong>), you use that number to pick one: 93 % 8 = 5. &quot;Alice&quot; goes straight into slot 5. No searching.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d0Bx9OArg63MEvsXm8wsDA.png" /></figure><p>That’s the entire core idea: <strong>turn a key into a number, use that number to pick a slot in an array, store it there.</strong> Everything below exists to handle the details and edge cases of that one idea.</p><h4>Where does the “number” actually come from?</h4><p>It starts with calling .hashCode() on the key — every Java object has one (inherited from Object), returning an int.</p><p>For String, it&#39;s a defined formula, not randomness:</p><pre>s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]</pre><p>Same string, same characters, always the same result. The one rule this depends on: <strong>equal objects must produce equal hash codes</strong> — if a.equals(b) is true, a.hashCode() must equal b.hashCode().</p><p>For your own classes, skipping hashCode() gives you Object&#39;s default — based on memory address, not content. That&#39;s almost always wrong for a map key, which is why the rule &quot;override equals() → override hashCode()&quot; exists.</p><p>One more detail: HashMap doesn’t use your raw hashCode() directly — it runs one more step on it first (we&#39;ll get to why, and what, in Step 5).</p><h3>Step 2: What happens when two keys land in the same bucket?</h3><p>With 16 buckets (the real Java default — more on that in a second) and potentially thousands of keys, two different keys <em>will</em> eventually hash into the same slot. This is a <strong>collision</strong> — not a bug, an expected and unavoidable outcome that HashMap is specifically designed to handle.</p><p><strong>The solution:</strong> each bucket doesn’t hold one item — it holds a small <em>list</em> of items.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tozaw6gKb1DrS4TBx0FykA.png" /></figure><p>This is called <strong>chaining</strong>. Each item in the chain holds its key, its value, and a pointer to the <em>next</em> item in that same bucket (or nothing, if it’s last).</p><p>Why this doesn’t ruin the speed benefit: you still jump straight to the right bucket using the hash. You only search <em>within</em> that one bucket’s short chain — not the whole map. As long as collisions stay rare and chains stay short, this stays close to instant. The one failure mode — a chain growing long — is exactly what Step 3 handles.</p><h4>Is the bucket count always 8? Is it always a linked list?</h4><p>Two good questions worth answering directly:</p><p><strong>Bucket count:</strong> 8 was a simplified example above — the real default starting capacity in Java is <strong>16</strong>. It grows as you add entries (Step 4), and you can specify your own starting size. One fixed rule: capacity is always a <strong>power of two</strong> (16, 32, 64…) — never an arbitrary number. That constraint is what makes a fast trick in Step 5 possible.</p><p><strong>Why a linked list for chaining, and not something like a </strong><strong>HashSet?</strong> Mostly to avoid circular dependency and overhead:</p><ul><li>HashSet is actually <em>implemented using a </em><em>HashMap</em> internally — using it to implement chaining inside HashMap would mean HashMap depends on something that depends on HashMap.</li><li>Even ignoring that, a HashSet means hashing <em>again</em> inside every bucket, plus a second hash table per bucket — far too much overhead for what&#39;s usually 1–3 items.</li><li>A linked list is the simplest structure that does exactly what’s needed: hold a handful of items, let you walk through them. Minimal memory per node (key, value, hash, one pointer).</li></ul><h3>Step 3: What happens when a chain gets too long?</h3><p>Picture a bucket that’s accumulated 20 entries — bad luck, or a poorly-written hashCode() that keeps colliding. Looking something up in that bucket now means walking through up to 20 items linearly. You&#39;re back to Step 1&#39;s slow problem, just shrunk to one bucket.</p><p><strong>Java’s fix:</strong> once a bucket’s chain reaches <strong>8 entries</strong>, it converts from a linked list into a <strong>red-black tree</strong> (a self-balancing binary search tree).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ofskkKrBO-fYYm1YZOzjLg.png" /></figure><p>In a list of 8 items, worst-case lookup is up to 8 comparisons — no internal order, so every item must be checked. In a balanced tree of 8 items, worst case is closer to 3, because each step rules out half the remaining items (like binary search). The gap widens with scale: 1,000 items in a list needs up to 1,000 checks; in a tree, about 10.</p><p>One condition: treeification only happens if the bucket array has at least <strong>64</strong> buckets total. Below that, Java prefers to <strong>resize</strong> the whole table first — a long chain in a small table is more likely a capacity problem than a bad hash (this is the bridge into Step 4). It’s also reversible: if entries drop back to 6, the bucket converts back to a list (trees cost more memory per node, not worth it for a near-empty bucket).</p><p>This mechanism is also Java 8’s fix for hash-flooding denial-of-service attacks, where someone deliberately crafts colliding keys to degrade a HashMap to a slow linked list.</p><h3>Step 4: Why and when does the bucket array grow?</h3><p>More buckets means fewer collisions — each bucket holds fewer items, chains stay short. But starting huge would waste memory for a map that only ever holds 5 items. So HashMap starts small (16 buckets) and grows only as needed.</p><p><strong>The trigger — load factor:</strong> the ratio size / capacity. Default is <strong>0.75</strong>. The moment size exceeds capacity × 0.75, a resize fires automatically.</p><p>Example: capacity 16 → 16 × 0.75 = 12. Insert the 13th entry, and resize happens before put() even returns.</p><p><strong>What resize does:</strong> capacity <strong>doubles</strong> (16 → 32 → 64…), always staying a power of two. Then every existing entry has to be re-placed into the new array — because a key’s bucket index depended on the <em>old</em> capacity, and that index may now be wrong for the new, bigger one.</p><p><strong>Why this is tolerable:</strong> resize doesn’t happen on every insert, only when the threshold is crossed. Inserting a million items might resize ~17 times total, not a million. This is <strong>amortized cost</strong> — individual inserts stay fast; the occasional expensive resize averages out to a low cost per insert.</p><p>Practical consequence: if you already know roughly how many items you’ll store, you can skip these intermediate resizes entirely by pre-sizing the map (covered in the appendix below).</p><h3>Step 5: The trick that makes resizing cheap</h3><p>This is the detail most people don’t know, and it’s the one that ties everything above together.</p><p><strong>The naive approach</strong> to re-placing entries after resize would be recomputing hash % newCapacity from scratch for every entry — division/modulo is relatively slow, and you&#39;d redo it for everything on every resize.</p><p><strong>Java avoids this because capacity is always a power of two.</strong> Doubling capacity (16 → 32) is the same as adding exactly <strong>one more bit</strong> to the number used for bucket selection: capacity 16 (2^4) uses the last 4 bits; capacity 32 (2^5) uses the last 5.</p><p>So any entry already placed at old index i can only land in one of <strong>two</strong> possible new positions:</p><ul><li><strong>Same index </strong><strong>i</strong> — if that newly-relevant bit is 0</li><li><strong>i + oldCapacity</strong> — if that bit is 1</li></ul><p>No full recomputation. Just check one bit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PUC3LZIRgG3KL5DzRdCfow.png" /></figure><p>An entry in old bucket 5 lands in either new bucket 5 or new bucket 21 (5 + 16) — nowhere else. This is O(1) work per entry during resize, and it&#39;s why chains tend to split roughly in half rather than scattering unpredictably.</p><h4>How “check one bit” actually happens: masking</h4><p>The bucket index isn’t computed with % at all — it&#39;s (capacity - 1) &amp; hash, using bitwise AND. This works <em>only</em> because capacity is a power of two: capacity - 1 in binary is then a clean run of 1s (e.g. 16 - 1 = 15 = 00001111), and ANDing any number against that keeps only its last 4 bits, zeroing everything above. That number (capacity - 1) is called a <strong>bitmask</strong> — &quot;masking&quot; means selectively keeping or clearing specific bits, the same way masking tape covers the parts you don&#39;t want painted. (capacity-1) &amp; hash gives the <em>same result</em> as hash % capacity, but only when capacity is a power of two — that&#39;s the entire reason Java constrains capacity the way it does.</p><h4>Why “spread” the hash first?</h4><p>Masking only ever looks at the last few bits. But a raw hashCode() is a full 32-bit number, and for some objects, most of the variation between different keys&#39; hashes lives in the <em>higher</em> bits — which masking would completely ignore, wasting that information and causing avoidable collisions.</p><p>The fix, applied before masking:</p><pre>spread = hash ^ (hash &gt;&gt;&gt; 16)</pre><p>This shifts the hash right by 16 bits (moving the upper half down into the lower half) and XORs it with the original — folding high-bit information into the low bits that masking actually uses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bMeI7z-blTVa6ZA8obFWAQ.png" /></figure><p>Trace it: spread hash 01011101, mask 00001111 (capacity 16), AND gives 00001101 = bucket <strong>13</strong>. Only the last 4 bits decided the outcome — and spreading is what guarantees those 4 bits carry information from the <em>whole</em> hash, not just whatever happened to land at the bottom.</p><h3>Putting it together</h3><p>Hashing turns a key into a jump instead of a search (Step 1). Collisions are handled by chaining entries in the target bucket (Step 2). A chain that grows too long upgrades to a tree so worst-case lookup stays fast (Step 3). The table grows when it gets too full, to keep chains short in the first place (Step 4). And the entire system stays cheap because capacity is always a power of two — turning both bucket selection and resize redistribution into simple bit operations instead of expensive arithmetic (Step 5).</p><p>None of these five steps is optional trivia — each one exists because the step before it would break down without it. Laid out as one system, it’s actually a closed loop:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n2PUovavISFhHDWVwZfhsA.png" /></figure><p>Hashing decides where an entry <em>starts</em>. Collisions decide how it’s <em>found</em> once it’s there. And resizing is the feedback loop that keeps the first two parts honest — every time capacity doubles, the mask changes, which is why every entry has to be re-placed. Nothing in this diagram is independent of anything else; that interdependency is exactly what a “tell me how HashMap works” question is really probing for.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P4uDMk2nEQAUteYSMfO8bA.png" /></figure><h3>Appendix: side questions that came up along the way</h3><p>These are useful, but weren’t required to follow the main thread above.</p><h4>How do I declare a HashMap when I already know how many items it’ll hold?</h4><pre>Map&lt;String, String&gt; map = new HashMap&lt;&gt;(64);</pre><p>The subtlety: 64 is the bucket array size, not the number of items before a resize. Resize triggers at size &gt; capacity × 0.75 — so new HashMap&lt;&gt;(100) for 100 expected items still resizes around the 75th. To size it so it never resizes:</p><pre>int expectedSize = 100;<br>Map&lt;String, String&gt; map = new HashMap&lt;&gt;((int) (expectedSize / 0.75) + 1);</pre><p>Java 19+ added a shortcut that does this math for you:</p><pre>Map&lt;String, String&gt; map = HashMap.newHashMap(100);</pre><p>Worth doing when you know you’re loading a large, known quantity of data — it avoids several unnecessary resizes (each of which re-places every existing entry) along the way.</p><p><strong>What this actually allocates is a two-step calculation, and the second step surprises people.</strong> First, Java computes ceil(numMappings / loadFactor) — for 100 entries, ceil(100 / 0.75) = 134. Then, because capacity must always be a power of two (Step 5), that 134 gets rounded up to the next power of two: <strong>256</strong>. So HashMap.newHashMap(100) doesn&#39;t give you &quot;just enough&quot; buckets — it gives you 256, nearly double the raw load-factor math, purely because of the power-of-two constraint. Your own manual formula ((int)(expectedSize / 0.75) + 1) goes through this exact same rounding internally, so both approaches land on the same final table size — newHashMap() just saves you the arithmetic.</p><h4>Why not just use a lower load factor, if some collisions are fine?</h4><p>A fair question: if 100 entries don’t strictly need 256 buckets, why not deliberately size smaller — say 50 buckets, load factor 2.0 — and accept a few more collisions? You can, and it’s a legitimate tuning choice:</p><pre>Map&lt;String, String&gt; map = new HashMap&lt;&gt;(50, 2.0f); // explicit load factor</pre><p>Collisions aren’t a correctness problem — a chain of 5 still works, it’s just slower to walk than a chain of 1. Load factor is the tuning knob for <em>memory saved vs. average lookup speed</em>, and 0.75 is simply a general-purpose default, not evidence that collisions are assumed to be zero.</p><p>The subtler reason the default leans generous: hashing isn’t perfectly even. Even at load factor 1.0, the same statistical clustering behind the birthday paradox means some buckets end up empty and others end up with 3–4 entries, purely from variance — not a bad hash function. A lower load factor (more buckets relative to entries) keeps that realistic worst-case bucket short, not just the average. It also keeps you comfortably above the 64-bucket floor treeification needs (Step 3) to kick in as a safety net if a chain does get unlucky. Tighter sizing (like load factor 2.0) is a perfectly valid choice when memory matters more than tail-latency — Java just doesn’t assume that’s your priority by default.</p><h3>Coming in Part 2: ConcurrentHashMap</h3><p>Everything above describes single-threaded HashMap. The moment multiple threads read and write concurrently, plain HashMap breaks — lost updates, and in Java 7, an infamous infinite-loop-on-resize bug.</p><p>ConcurrentHashMap fixes this with <strong>bucket-level locking</strong> instead of one lock for the whole map: reads are lock-free (thanks to volatile fields), and writes only block other threads trying to write to the <em>same bucket</em> — not the whole table. <a href="https://sandeep-rai.medium.com/concurrenthashmap-step-by-step-how-java-makes-hashmap-thread-safe-without-one-big-lock-part-2-5b60c99e4a64">Part 2</a> builds that up the same way, one step at a time, starting from exactly the bucket-array picture this post just established.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dd51b0c57a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot AutoConfiguration and How to create your own]]></title>
            <link>https://medium.com/javarevisited/spring-boot-autoconfiguration-and-how-to-create-your-own-ddc16120e4db?source=rss-806d72b9e281------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddc16120e4db</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[configuration]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sandeep Rai]]></dc:creator>
            <pubDate>Tue, 02 Apr 2024 15:11:33 GMT</pubDate>
            <atom:updated>2024-04-02T15:11:33.084Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn about the real reason behind Spring Boot’s magic and create your own custom Spring Boot AutoConfiguration.</h4><figure><img alt="Spring Boot AutoConfiguration" src="https://cdn-images-1.medium.com/max/1024/1*tR1hlNGhdVjt_2e4_yGnCw.png" /></figure><p>If you’ve worked with Spring Boot, you’ve likely marveled at how effortlessly things fall into place. With just a Spring Boot starter, a few properties, or a dependency, Spring Boot handles the setup of numerous beans and features automatically (or as some might say, <em>automagically</em>). Much of this ‘magic’ can be attributed to one key Spring Boot module: spring-boot-autoconfigure.</p><p>In this article, we’ll discuss the internals of spring-boot-autoconfigure and learn how to create our own autoconfigurations. By the end, you’ll understand how Spring Boot’s magic works, the role of spring-boot-autoconfigure module, and create custom autoconfigurations (and hopefully inspire you to create you own).</p><h3>spring-boot-autoconfigure</h3><p>The <a href="https://github.com/spring-projects/spring-boot/tree/main/spring-boot-project/spring-boot-autoconfigure">source code</a> of spring-boot-autoconfigure project can be a good starting point to see what it is and how it works. It consists of a number of <a href="https://github.com/spring-projects/spring-boot/tree/main/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure">packages</a> with auto-configuration classes and a file called <a href="https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot-autoconfigure/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports">org.springframework.boot.autoconfigure.AutoConfiguration.imports</a> which lists all auto-configuration classes that are loaded during startup of a Spring Boot application.</p><p>A snippet from org.springframework.boot.autoconfigure.AutoConfiguration.imports file:</p><pre>org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration<br>org.springframework.boot.autoconfigure.aop.AopAutoConfiguration<br>org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration<br>org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration<br>org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration<br>org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration<br>org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration<br>org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration<br>org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration<br>org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration<br>org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration<br>org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration<br>org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration<br>org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveDataAutoConfiguration<br>org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveRepositoriesAutoConfiguration<br>org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration<br>org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration<br>org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveDataAutoConfiguration<br>...</pre><p>These classes have configuration to create beans, mostly based on certain <strong>conditions</strong>. The major conditions are the following:</p><ul><li>Whether a dependency is present on the classpath.</li><li>Whether a property is defined.</li><li>Whether a bean has already been defined by the user.</li></ul><p>There are more conditions, but these are the main ones. They are specified using @Conditional annotations.</p><p>Here is an example for an auto-configuration <a href="https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfiguration.java">class</a> with conditions:</p><pre>@AutoConfiguration(after = { HibernateJpaAutoConfiguration.class, TaskExecutionAutoConfiguration.class })<br>@ConditionalOnBean(DataSource.class)<br>@ConditionalOnClass(JpaRepository.class)<br>@ConditionalOnMissingBean({ JpaRepositoryFactoryBean.class, JpaRepositoryConfigExtension.class })<br>@ConditionalOnProperty(prefix = &quot;spring.data.jpa.repositories&quot;, name = &quot;enabled&quot;, havingValue = &quot;true&quot;,<br>  matchIfMissing = true)<br>@Import(JpaRepositoriesImportSelector.class)<br>public class JpaRepositoriesAutoConfiguration {...</pre><ol><li>@AutoConfiguration: Tells that this is an auto-configuration. This is similar to @Configuration. The after indicates that this should be run after those two configurations.</li><li>@ConditionalOnBean: Run this configuration only if DataSource bean is already created.</li><li>@ConditionalOnClass: JpaRepository class should exist on the classpath, which means the spring-data-jpa dependency should be present.</li><li>@ConditionalOnMissingBean: The beans specified shouldn’t be defined by the user in the application.</li><li>@ConditionalOnProperty: The property spring.data.jpa.repositories.enabled should either be true or not defined at all.</li></ol><p>Once all these conditions are met, beans defined inside this class are created.</p><p>Some auto-configuration classes do not have @Conditional annotations, which means they are configured unconditionally. E.g. SslAutoConfiguration, ApplicationAvailabilityAutoConfiguration.</p><p>Exploring the spring-boot-autoconfigure project can demystify a lot of the ‘magic’ that happens during startup of a Spring Boot application.</p><h3>Creating your own AutoConfiguration</h3><p>You can create auto-configurations for beans that multiple projects in your organization need to use. Typically, these would be beans that are not auto-configured by spring, but needed by your projects based on conditions discussed earlier like a dependency on the classpath or property values.</p><p>Let us try auto-configuring <a href="https://github.com/davidmoten/rxjava3-jdbc">rxjava3-jdbc</a> <a href="https://github.com/davidmoten/rxjava3-jdbc/blob/master/rxjava3-jdbc/src/main/java/org/davidmoten/rxjava3/jdbc/Database.java">Database</a> bean. The first step is to create a project that has the auto-configuration that can then be added as a dependency in other projects. So, let’s create a <a href="https://github.com/rai-sandeep/java/tree/main/spring/boot/autoconfigure/sandeeprai-spring-boot-autoconfigure">maven project</a> with the rxjava3-jdbc and spring-boot-autoconfigure dependencies.</p><pre>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-autoconfigure&lt;/artifactId&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;com.github.davidmoten&lt;/groupId&gt;<br>            &lt;artifactId&gt;rxjava3-jdbc&lt;/artifactId&gt;<br>            &lt;version&gt;0.1.4&lt;/version&gt;<br>            &lt;optional&gt;true&lt;/optional&gt;<br>        &lt;/dependency&gt;</pre><p>Notice that rxjava3-jdbc dependency is optional since we want the user to decide if he wants to use it in his project or not. If he has the dependency, the condition will match and the bean will be created (think @Conditional).</p><p>It’s time to create the custom auto-configuration class:</p><pre>@AutoConfiguration<br>@ConditionalOnClass(Database.class)<br>@EnableConfigurationProperties(RxJava3JdbcDatabaseProperties.class)<br>public class RxJava3JdbcDatabaseAutoConfiguration {<br><br>    @Bean<br>    public Database database(RxJava3JdbcDatabaseProperties properties) {<br>        return Database.nonBlocking()<br>                .url(https://medium.com/properties.getUrl())<br>                .user(properties.getUsername())<br>                .password(properties.getPassword())<br>                .maxPoolSize(properties.getMaxPoolSize())<br>                .build();<br>    }<br>}</pre><p>Note the @AutoConfiguration annotation and a @Conditional for checking if the Database class that comes from rxjava3-jdbc dependency is on the classpath. If these conditions match, it maps some custom properties to RxJava3JdbcDatabaseProperties class and creates the Database bean.</p><pre>@ConfigurationProperties(prefix = &quot;rxjava3.jdbc.database&quot;)<br>public class RxJava3JdbcDatabaseProperties {<br>    private String username;<br>    private String password;<br>    private String url;<br>    private int maxPoolSize;<br><br>//getters and setters<br>...</pre><p>The last step is to create a new file named org.springframework.boot.autoconfigure.AutoConfiguration.imports under src/main/resources/META-INF/spring and add the fully qualified name of the auto-configuration class:</p><pre>com.sandeeprai.springboot.autoconfigure.data.rxjava.RxJava3JdbcDatabaseAutoConfiguration</pre><p>Add this project as a dependency in another project to see the auto-configuration work.</p><h3>Seeing it in Action</h3><p>In order to use the auto-configuration class, run mvn clean install on the above project (to add it the local .m2 repository), and import the dependency in a different project.</p><p>I created a <a href="https://github.com/rai-sandeep/java/tree/main/spring/boot/autoconfigure/springboot-autoconfigure-demo">demo project</a> and added the above auto-configuration dependency along with rxjava3-jdbc which has the Database class that needs to be auto-configured:</p><pre>  &lt;dependency&gt;<br>   &lt;groupId&gt;com.github.davidmoten&lt;/groupId&gt;<br>   &lt;artifactId&gt;rxjava3-jdbc&lt;/artifactId&gt;<br>   &lt;version&gt;0.1.4&lt;/version&gt;<br>  &lt;/dependency&gt;<br><br>  &lt;dependency&gt;<br>   &lt;groupId&gt;com.sandeeprai&lt;/groupId&gt;<br>   &lt;artifactId&gt;sandeeprai-spring-boot-autoconfigure&lt;/artifactId&gt;<br>   &lt;version&gt;1.1.0&lt;/version&gt;<br>  &lt;/dependency&gt;</pre><p>The main class is a simple Spring Boot application main class:</p><pre>@SpringBootApplication<br>public class SpringbootAutoconfigureDemoApplication {<br><br> public static void main(String[] args) {<br>  SpringApplication.run(SpringbootAutoconfigureDemoApplication.class, args);<br>...</pre><p>Add the custom properties needed for configuring the Database bean to application.properties:</p><pre>rxjava3.jdbc.database.username=sa<br>rxjava3.jdbc.database.password=sa<br>rxjava3.jdbc.database.url=jdbc:h2:mem:<br>rxjava3.jdbc.database.max-pool-size=10</pre><p>This will configure a Database bean that connects to an in-memory h2 database. You will also need the h2 dependency for this to fully work.</p><p>Now start the application with the --debug flag to see Spring Boot’s auto-configuration conditions evaluation report in the console:</p><pre>============================<br>CONDITIONS EVALUATION REPORT<br>============================<br><br><br>Positive matches:<br>-----------------<br><br>   ApplicationAvailabilityAutoConfiguration#applicationAvailability matched:<br>      - @ConditionalOnMissingBean (types: org.springframework.boot.availability.ApplicationAvailability; SearchStrategy: all) did not find any beans (OnBeanCondition)<br>...<br><br>   RxJava3JdbcDatabaseAutoConfiguration matched:<br>      - @ConditionalOnClass found required class &#39;org.davidmoten.rxjava3.jdbc.Database&#39; (OnClassCondition)<br>...<br><br>Negative matches:<br>-----------------<br><br>   ActiveMQAutoConfiguration:<br>      Did not match:<br>         - @ConditionalOnClass did not find required class &#39;jakarta.jms.ConnectionFactory&#39; (OnClassCondition)<br>...<br><br>Exclusions:<br>-----------<br><br>    None<br><br><br>Unconditional classes:<br>----------------------<br><br>    org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration<br>...</pre><p>This lists each auto-configured bean created, beans that were not created, the reason for each positive and negative match, exclusions and unconditionally auto-configured beans. The list of positive matches includes our custom auto-configured bean since we have included the rxjava3-jdbc dependency. If you remove the dependency and re-run the project, it should appear under the negative matches section.</p><h3>FAQ</h3><p>Q: Should I use @AutoConfiguration or @Configuration annotation on my auto-configuration class?</p><p>A: As per Spring Boot’s <a href="https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.7.0-M2-Release-Notes#new-autoconfiguration-annotation">release notes</a>, @AutoConfiguration should be used to annotate top-level auto-configuration classes. The annotation itself does not make the class a candidate for auto-configuration. You will still need to add it to the org.springframework.boot.autoconfigure.AutoConfiguration.imports file mentioned earlier. In this respect, it is similar to @Configuration (the <a href="https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/autoconfigure/AutoConfiguration.html">javadoc</a> states this as well: <em>Auto-configuration classes are regular </em><a href="https://docs.spring.io/spring-framework/docs/6.1.5/javadoc-api/org/springframework/context/annotation/Configuration.html"><em>@Configuration</em></a><em> with the exception that Configuration#proxyBeanMethods() proxyBeanMethods is always </em><em>false</em>). However, @AutoConfiguration makes more sense in this context, is the standard now and makes it explicit that the class is meant for auto-oncfiguration.</p><p>Q: Should I add my custom auto-configuration class to org.springframework.boot.autoconfigure.AutoConfiguration.imports or spring.factories file?</p><p>A: Even though many tutorials refer to using spring.factories file, it is now deprecated and META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports file should be used instead as per Spring Boot’s <a href="https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.7.0-M2-Release-Notes#deprecations-in-spring-boot-27">release notes</a>.</p><p>Q: When should I create and use custom auto-configurations?</p><p>A: Create custom auto-configurations if Spring Boot does not auto-configure a bean that is used in multiple projects in your organization and needs to be configured based on certain conditions. For simpler scenarios, @Configuration class within your application code would be the way to go.</p><h3>Source Code</h3><p>The source code for the custom auto-configuration and the demo can be found on <a href="https://github.com/rai-sandeep/java/tree/main/spring/boot/autoconfigure">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddc16120e4db" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/spring-boot-autoconfiguration-and-how-to-create-your-own-ddc16120e4db">Spring Boot AutoConfiguration and How to create your own</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GoF Design Patterns: An Overview]]></title>
            <link>https://sandeep-rai.medium.com/gof-design-patterns-an-overview-70f18eae8032?source=rss-806d72b9e281------2</link>
            <guid isPermaLink="false">https://medium.com/p/70f18eae8032</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[gof-design-patterns]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Sandeep Rai]]></dc:creator>
            <pubDate>Mon, 14 Aug 2023 06:46:44 GMT</pubDate>
            <atom:updated>2023-08-14T06:58:55.557Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="GoF Design Patterns" src="https://cdn-images-1.medium.com/max/1024/1*WwNP1XQdclU7Yf7dlbjXvQ.jpeg" /></figure><h3>What are GoF Design Patterns</h3><p>GoF design patterns are a set of 23 well-defined and time-tested <strong>solutions to common software design problems</strong>. These patterns encapsulate proven best practices and principles for structuring code, improving maintainability, and promoting reusability. By employing these patterns, developers can streamline the design process and create more flexible and robust software systems.</p><h3>Why is it Named “Gang of Four”</h3><p>The term “Gang of Four” refers to the four authors of the influential book “Design Patterns: Elements of Reusable Object-Oriented Software,” published in 1994. The authors, <strong>Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides</strong>, collectively known as the “Gang of Four,” formalized these patterns and introduced them to the software development community.</p><h3>GoF Design Pattern Categories</h3><p>The GoF design patterns are divided into three categories based on their primary purpose.</p><ol><li><strong>Creational</strong>: Creational patterns focus on the process of <strong>object creation</strong>, providing mechanisms for creating objects in a manner that enhances flexibility and decouples the client code from the actual classes being instantiated.</li><li><strong>Structural</strong>: Structural patterns address <strong>how classes and objects are composed to form larger structures</strong> while keeping the system flexible and efficient. These patterns enhance the relationships between classes and objects.</li><li><strong>Behavioral</strong>: Behavioral patterns focus on communication between objects, defining <strong>how objects interact and cooperate</strong> to accomplish various tasks. These patterns emphasize the delegation of responsibilities and collaborations between classes.</li></ol><figure><img alt="GoF Design Pattern Categories" src="https://cdn-images-1.medium.com/max/1024/1*nlKXa7OFq2_d-Q-X4BAhlw.png" /><figcaption>GoF Design Pattern Categories</figcaption></figure><h3>Creational Design Patterns</h3><ol><li><strong>Singleton</strong>: Ensure a class has only one instance while providing a global point of access to that instance. Useful for managing shared resources or centralized configurations.</li><li><strong>Factory Method</strong>: Define an interface for creating objects, but let subclasses decide which class to instantiate. Enables loose coupling by delegating the responsibility of object creation to subclasses.</li><li><strong>Abstract Factory</strong>: Provide an interface for creating families of related or dependent objects without specifying their concrete classes. Ensures consistency and compatibility among object groups.</li><li><strong>Builder</strong>: Separate the construction of a complex object from its representation, allowing the same construction process to create different representations. Useful for creating complex objects step by step.</li><li><strong>Prototype</strong>: Specify the kind of objects to create using a prototypical instance and create new objects by copying this prototype. Simplifies object creation when instances have similar structures.</li></ol><h3>Structural Design Patterns</h3><ol><li><strong>Adapter</strong>: Convert the interface of a class into another interface that clients expect. Allows incompatible classes to work together by providing a common interface.</li><li><strong>Bridge</strong>: Decouple an abstraction from its implementation, allowing both to evolve independently. Useful when you want to avoid a permanent binding between abstraction and implementation.</li><li><strong>Composite</strong>: Compose objects into tree structures to represent part-whole hierarchies. Clients can treat individual objects and compositions uniformly.</li><li><strong>Decorator</strong>: Attach additional responsibilities to objects dynamically, providing a flexible alternative to subclassing. Enhances object behavior without altering its class.</li><li><strong>Facade</strong>: Provide a simplified interface to a complex subsystem, making it easier to use. Hides the complexities of a system and offers a more user-friendly interface.</li><li><strong>Flyweight</strong>: Share objects to support large numbers of similar objects efficiently. Reduces memory consumption by sharing common state.</li><li><strong>Proxy</strong>: Control access to an object by providing a surrogate or placeholder, allowing additional behavior to be introduced when accessing the object.</li></ol><h3>Behavioral Design Patterns</h3><ol><li><strong>Chain of Responsibility</strong>: Create a chain of receiver objects, allowing a request to pass along the chain until it’s handled by an appropriate handler. Decouples sender and receiver.</li><li><strong>Command</strong>: Encapsulate a request as an object, allowing parameterization of clients with different requests, queuing, logging, and undo functionality.</li><li><strong>Interpreter</strong>: Provide a way to evaluate language grammar or expressions. Converts a language into a format that can be interpreted by an interpreter.</li><li><strong>Iterator</strong>: Provide a way to access elements of a collection without exposing its underlying representation. Offers a uniform way to traverse various collections.</li><li><strong>Mediator</strong>: Define an object that centralizes communication among objects, promoting loose coupling and reducing direct connections between components.</li><li><strong>Memento</strong>: Capture an object’s internal state without exposing its internals, enabling it to be restored to a previous state.</li><li><strong>Observer</strong>: Define a one-to-many dependency between objects so that when one object changes state, its dependents are notified and updated automatically.</li><li><strong>State</strong>: Allow an object to change its behavior when its internal state changes. Encapsulates state-specific behavior and avoids conditional statements.</li><li><strong>Strategy</strong>: Define a family of interchangeable algorithms, encapsulating each algorithm separately and making them interchangeable. Allows selecting an algorithm at runtime.</li><li><strong>Template Method</strong>: Define the structure of an algorithm but allow subclasses to override specific steps. Promotes reusability by separating common and specific code.</li><li><strong>Visitor</strong>: Define a new operation without changing the classes of elements on which it operates. Enables adding new behaviors to existing classes without modifying their structure.</li></ol><h3>Do GoF Design Patterns only apply to Object-Oriented Programming</h3><p>GoF design patterns were originally conceived for Object-Oriented Programming (OOP). However, the underlying principles and concepts can be applied to other programming paradigms as well. Functional programming, for example, can benefit from some design patterns, albeit with adjustments to fit its characteristics. However, the patterns may need adaptation to accommodate different language features and paradigms.</p><p>GoF design patterns provide <strong>a common language and set of solutions for addressing recurring software design challenges</strong>. These patterns empower developers to create <strong>more maintainable, reusable, and flexible code</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70f18eae8032" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Saga Pattern Explained]]></title>
            <link>https://sandeep-rai.medium.com/saga-pattern-explained-4bde481fec59?source=rss-806d72b9e281------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bde481fec59</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[saga-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Sandeep Rai]]></dc:creator>
            <pubDate>Sun, 13 Aug 2023 06:59:54 GMT</pubDate>
            <atom:updated>2023-08-13T11:31:31.317Z</atom:updated>
            <content:encoded><![CDATA[<p>In the realm of microservices architecture, ensuring data consistency and integrity across distributed systems is a challenge. This is where the Saga pattern comes into play, offering an elegant solution to manage complex transactions.</p><h3>What is Saga Pattern and What Problem does it Solve</h3><p>In microservices architectures, a business operation might span multiple services, each responsible for specific tasks. Traditional <a href="https://en.wikipedia.org/wiki/ACID">ACID transactions</a> fall short in such distributed scenarios due to potential failures and the complexity of maintaining consistency.</p><p>The Saga pattern addresses this challenge by providing a way to handle long-running and multi-step transactions without relying on a central database or a monolithic approach.</p><h3>What Exactly is a Saga</h3><p>A saga is a <strong>sequence of local transactions orchestrated to complete a distributed transaction</strong>. Each local transaction is associated with a single service and can modify its own data. When multiple local transactions are combined, they form a saga.</p><h3>The Saga Coordinator</h3><p>The working of Saga Pattern in enabled by something called the <strong>Saga Coordinator</strong>.</p><p>The Saga Coordinator is a software component responsible for coordinating the execution of the Saga pattern within a distributed system. While it’s not a physical entity like a server or a physical machine, it’s a crucial piece of software that orchestrates the sequence of local transactions and ensures the integrity and consistency of the distributed transaction as a whole.</p><p>The Saga Coordinator is typically implemented as a service or module within your microservices ecosystem. It communicates with the various services involved in the saga, manages the state of each step, triggers compensating actions when needed, and tracks the overall progress of the saga. It’s responsible for making decisions based on the outcomes of local transactions and taking appropriate actions to maintain data integrity.</p><p>The implementation of a Saga Coordinator can vary based on the technologies and frameworks you’re using. It might involve components like message queues, event-driven architecture, or custom coordination logic tailored to your specific needs.</p><h3>How does Saga Pattern Work</h3><ol><li><strong>Initiation</strong>: A saga is initiated by the saga coordinator when a complex transaction starts.</li><li><strong>Local Transactions</strong>: Each service performs its local transaction and communicates its status to the coordinator.</li><li><strong>Compensating Actions</strong>: If a local transaction fails, compensating actions are executed to undo the changes made by previous steps.</li><li><strong>State Management</strong>: The coordinator tracks the state of each local transaction and ensures the saga’s progress.</li><li><strong>Completion and Consistency</strong>: Once all local transactions are successful, the saga is completed. If a step fails, compensating actions bring the system back to a consistent state.</li></ol><h3>A Real-World Example of Saga Pattern in Action</h3><p><strong>Scenario: Order Processing in an E-commerce Platform</strong></p><p>Order processing in an e-commerce platform involves multiple steps across different services: inventory management, payment processing, and shipping. The challenge is to ensure that if any step fails, the system remains consistent and the user is informed appropriately.</p><figure><img alt="Saga Pattern for Order Processing" src="https://cdn-images-1.medium.com/max/687/1*ZBwxag3DPOSQOyRnE2Oskg.png" /><figcaption>Saga Pattern for Order Processing</figcaption></figure><ol><li><strong>Initiation</strong>: A user places an order, triggering a complex transaction that involves inventory reservation, payment authorization, and shipping arrangement.</li><li><strong>Saga Coordinator</strong>: The Saga Coordinator, a software component within the microservices ecosystem, is responsible for overseeing this transaction. It initiates the saga and communicates with the services involved.</li><li><strong>Local Transactions:<br>- </strong>Inventory Management Service: The inventory service reserves the ordered items and communicates the status to the coordinator.<br>- Payment Processing Service: The payment service authorizes the payment and updates the status.<br>- Shipping Service: The shipping service arranges for product shipment and notifies the coordinator.</li><li><strong>Communication and Coordination</strong>:<br>- The Saga Coordinator maintains the state of each step and communicates with the services to ensure they complete their actions.<br>- If all services confirm successful completion, the coordinator marks the saga as successful.</li><li><strong>Compensating Actions</strong>:<br>- If a service fails or indicates a problem, the coordinator triggers compensating actions.<br>- For instance, if payment authorization fails, the coordinator would instruct the inventory service to release the reserved items and inform the user about the issue.</li><li><strong>Data Integrity</strong>: The Saga Coordinator ensures that the system remains in a consistent state, even if a step fails. It might initiate retries or further actions to rectify the situation.</li><li><strong>Completion</strong>: Once all local transactions are successfully completed, the coordinator marks the saga as finished. The user receives a confirmation that their order is processed.</li></ol><h3>Drawbacks of Saga Pattern</h3><p>While the Saga pattern offers an effective solution, it introduces complexities in terms of coordination and handling various failure scenarios. <strong>Implementing a reliable saga coordinator and designing compensating actions</strong> can be challenging and time-consuming.</p><h3>When to use Saga Pattern and when not to</h3><p><strong>Use Saga Pattern When:</strong></p><ul><li>Transactions involve multiple services and maintaining consistency is crucial.</li><li>Compensation logic can be defined for each local transaction to ensure data integrity.</li><li>You are ready to handle the added complexity of coordinating and managing sagas.</li></ul><p><strong>Avoid Saga Pattern When:</strong></p><ul><li>The transactions are relatively simple and involve only one service.</li><li>The added complexity of sagas outweighs the benefits in your specific use case.</li><li>The system is not equipped to handle the coordination and compensating actions.</li></ul><p>Saga pattern enables the management of distributed transactions using <strong>local transactions</strong> and <strong>compensating actions</strong>, while maintaining data consistency across multiple services. However, it may not be the right fit for all use cases as explained above.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bde481fec59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Really Are Microservices: Advantages, Challenges, and Trade-offs]]></title>
            <link>https://sandeep-rai.medium.com/what-really-are-microservices-advantages-challenges-and-trade-offs-e5831aad40b2?source=rss-806d72b9e281------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5831aad40b2</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Sandeep Rai]]></dc:creator>
            <pubDate>Sat, 12 Aug 2023 08:16:48 GMT</pubDate>
            <atom:updated>2023-08-13T07:05:16.303Z</atom:updated>
            <content:encoded><![CDATA[<h3>What Really are Microservices: Advantages, Challenges, and Trade-offs</h3><h3>What Are Microservices?</h3><p>Microservices is an architectural style that<strong> structures an application as a collection of small, independent services, each focused on a specific business capability</strong>.</p><p>Unlike monolithic applications, which consist of tightly coupled components, microservices enable developers to build, deploy, and scale individual services independently.</p><h3>Key Characteristics and Concepts of Microservices</h3><ol><li><strong>Decomposition</strong>: Microservices break down a monolithic application into smaller services, each with a specific business function.</li><li><strong>Loose Coupling</strong>: Services communicate through well-defined APIs, allowing changes to one service without affecting others.</li><li><strong>Independent Deployment</strong>: Each microservice can be developed, tested, and deployed independently, enabling faster release cycles.</li><li><strong>Scalability</strong>: Services can be scaled individually to handle varying workloads.</li><li><strong>Technology Diversity</strong>: Different services can use distinct technologies, frameworks, and databases as required.</li><li><strong>Resilience</strong>: Microservices are designed to handle failures in a way that doesn’t bring down the entire system.</li><li><strong>Continuous Integration/Deployment</strong>: Automation is crucial to ensure seamless integration, testing, and deployment.</li><li><strong>Monitoring and Observability</strong>: Tools for tracking performance and diagnosing issues are essential due to the distributed nature of microservices.</li></ol><h3>Benefits and Advantages of Microservices</h3><figure><img alt="Benefits and Advantages of Microservices Compared to Monolithic Applications" src="https://cdn-images-1.medium.com/max/1024/1*efWAnjCcKBVoVmGXvN7O-w.png" /><figcaption>Benefits and Advantages of Microservices Compared to Monolithic Applications</figcaption></figure><h3>Challenges of Microservices</h3><ol><li><strong>Complexity</strong>: Managing a network of interconnected services introduces operational complexity.</li><li><strong>Inter-Service Communication</strong>: Overreliance on network communication can introduce latency and bottlenecks.</li><li><strong>Data Consistency</strong>: Maintaining data consistency across services can be challenging.</li><li><strong>Service Discovery</strong>: Finding and connecting to services dynamically can be complex.</li><li><strong>Testing Complexity</strong>: Testing distributed systems requires more comprehensive strategies.</li><li><strong>Operational Overhead</strong>: Each service needs monitoring, scaling, and maintenance.</li></ol><h3>Trade-offs and How to Decide whether or not to use Microservices</h3><p>Deciding whether to adopt microservices is a critical architectural choice that involves weighing the benefits against the challenges and considering the specific context of a project. Microservices offer numerous advantages, but they also introduce challenges as discussed above.</p><figure><img alt="How to Decide whether or not to use Microservices" src="https://cdn-images-1.medium.com/max/1024/1*uLIGnSprUxmLAGLZ0gfcoQ.png" /><figcaption>How to Decide whether or not to use Microservices</figcaption></figure><p>The decision to adopt microservices should align with the project’s requirements, team capabilities, and long-term goals. As is the case with most architectural decisions, there’s no one-size-fits-all answer.</p><p>A hybrid approach is also possible, where you start with a monolithic application and gradually transition to microservices as the application’s complexity and user base grow.</p><h3>Common Problems related to Microservices and their Solutions</h3><figure><img alt="Common Problems related to Microservices and their Solutions" src="https://cdn-images-1.medium.com/max/1024/1*AiA1Nm76JdNb1pY9M2mnTA.png" /><figcaption>Common Problems related to Microservices and their Solutions</figcaption></figure><p>To know more about Saga Pattern, checkout this article: <a href="https://sandeep-rai.medium.com/saga-pattern-explained-4bde481fec59">Saga Pattern Explained</a>.</p><h3>Are Microservices an Architectural Style or a Design Pattern?</h3><p>Microservices are both an architectural style and a design pattern. They guide the higher-level decisions about how to structure an application and its components (architecture) and provide specific guidance on designing individual services for independence, scalability, and maintainability (design pattern).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5831aad40b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Funky FAANG to Motherly MAMAA]]></title>
            <link>https://sandeep-rai.medium.com/funky-faang-to-motherly-mamaa-6fcfe4f3f7d8?source=rss-806d72b9e281------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fcfe4f3f7d8</guid>
            <category><![CDATA[big-tech]]></category>
            <category><![CDATA[creative]]></category>
            <category><![CDATA[faang]]></category>
            <category><![CDATA[mamaa]]></category>
            <dc:creator><![CDATA[Sandeep Rai]]></dc:creator>
            <pubDate>Sat, 18 Jun 2022 11:56:34 GMT</pubDate>
            <atom:updated>2022-06-18T11:56:34.700Z</atom:updated>
            <content:encoded><![CDATA[<h4>WITCH is the sweetest</h4><p>Don’t blame me for the cringeworthy acronyms. <a href="https://en.wikipedia.org/wiki/Mad_Money">Mad money’s</a> <a href="https://en.wikipedia.org/wiki/Jim_Cramer">Jim Cramer</a> coined them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*aUPPMhMM52yDSu1k1TJD5Q.jpeg" /><figcaption>For those in the dark</figcaption></figure><p>FAANG: Facebook, Apple, Amazon, Netflix, Google</p><p>In 2021, <a href="https://about.fb.com/news/2021/10/facebook-company-is-now-meta/">Facebook changed their name to Meta</a>, thereby inadvertently removing their and FAANG’s alliteration with the F-word. FAANG died and MAANG was born.</p><p>MAANG: Meta, Apple, Amazon, Netflix, Google</p><p>But wait, shouldn’t we replace Google with its parent Alphabet? Would that make it MAANA? Time for another twist. <a href="https://fortune.com/2022/04/20/netflix-stock-earnings-faang-selloff-content-diversify/">Netflix didn’t seem like a proper fit</a> to many, hence they made the brutal decision to drop Netflix and onboard Microsoft.</p><p>MAMAA: Meta, Apple, Microsoft, Amazon, Alphabet</p><p>Though she sounds like motherly love, MAMAA is tough on you if you want to work for her and makes you go through several rounds of interview with high rejection rates. If you want to feel more welcome, choose the path of least resistance and try the more sinister sounding WITCH, just like I did!</p><blockquote>MAMAA is tough on me, so I choose WITCH!</blockquote><p>WITCH: Wipro, Infosys, TCS, CTS, HCL</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fcfe4f3f7d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Siddhartha: Book Summary]]></title>
            <link>https://sandeep-rai.medium.com/siddhartha-book-summary-82f96574376d?source=rss-806d72b9e281------2</link>
            <guid isPermaLink="false">https://medium.com/p/82f96574376d</guid>
            <category><![CDATA[hermann-hesse]]></category>
            <category><![CDATA[siddhartha]]></category>
            <category><![CDATA[book-summary]]></category>
            <category><![CDATA[peace]]></category>
            <category><![CDATA[philosophy]]></category>
            <dc:creator><![CDATA[Sandeep Rai]]></dc:creator>
            <pubDate>Sat, 24 Apr 2021 14:29:38 GMT</pubDate>
            <atom:updated>2021-04-24T14:29:38.604Z</atom:updated>
            <content:encoded><![CDATA[<p>Siddhartha is a philosophical fiction novel originally written in German by Hermann Hesse. Set in ancient India, it tells the story of a man named Siddhartha during the time of Gotama Buddha. About his journey in search of self-discovery, nirvana, the meaning of life.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*thZJvUWgXG8ErqqW7tw1vQ.jpeg" /></figure><p>Siddhartha, the son of a Brahmin, the handsome son, grows up learning, worshipping and meditating. The perfect Brahmin boy destined for greatness. Govinda, his beloved friend, his big fan, nurses the desire to be his follower. Siddhartha is everyone’s love and joy. But he, himself, is restless and discontent due to the thirst for wisdom. This feeling of not being able to fill his thirst for knowledge and enlightenment, meaning, to find Atman, takes him on a long and bumpy journey.</p><p>Because Siddhartha does not get what he is searching for, he decides to move out of his Brahmin life to join the Samanas — the ascetics who believe that a life of deprivation and wandering is the path to self-actualization. Govinda follows him.</p><p>After living with the Samanas, practicing their ways and becoming one of their best, he realizes that he is not going to reach his goal as a Samana. He and Govinda decide to leave the Samanas and embark on a journey to the enlightened teacher Gotama, the Buddha.</p><p>They are instantly mesmerized by Gotama’s words, teachings, manners and actions. Govinda decides to be his disciple. But Siddhartha decides not to, to Govinda’s pain and shock. Leaving Govinda in grief, he moves on. He understands that Gotama is truly enlightened, but also realizes that wisdom cannot be passed on by a teacher, and that he himself should learn it through his journey and personal experiences. This, he tells the enlightened Gotama in a direct conversation.</p><p>Alone and ready for vast personal experiences, he lets himself loose. He learns to enjoy and savour the beauties and joys of the world. The things he had abstained from. He feels it was foolish to have denied himself these joys, and his ways were wrong.</p><p>From that point begins his journey on a wild roller coaster. Starting with the ferryman who ferries him across a river, he travels through the forest to a city, and is enchanted by the beauty of Kamala, the courtesan. For her and her beauty, he transforms into a wealthy man, working as the partner of Kamaswami, a businessman.</p><p>Everything seems to be trivial to him except his love for Kamala. So many times, his superior knowledge leads him to look at other people’s lives and emotions with a mocking eye. The things that people do for silly things like money amuses him. He feels that they are all child-like and he cannot have those kinds of emotions. But with time and money, he loses the voice of his knowledge and becomes just like one of them. As years pass, lust, riches, luxury, servants, wine, meat and gambling become his ways. Till it all reaches a tipping point and he goes back to the forest and the river, leaving everything behind.</p><p>So disgusted he feels with what he had become, that he decides to fall into the river and end his life. The sound of ‘Om’ brings him back to sanity. Exhausted, he falls asleep by the river bank. His beloved friend from the past, Govinda, now a Budhist monk, finds him lying and guards him. Govinda does not recognize Siddhartha though. Once awake, Siddhartha thanks him and reveals his identity. Govinda, though delighted to see his friend, is confused by his rich clothes, finds it hard to trust in his words and moves on. Siddhartha falls in love with the beautiful river and stays at its banks at the ferryman’s hut.</p><p>The river and the ferryman Vasudeva bring a sense of calm to Siddhartha’s life and teach him many valuable lessons. His life is peaceful until Kamala re-enters, with her son, young Siddhartha. On her way to seeing Gotama, she is bitten by a snake. She is ferried to the hut by Vasudeva, where she reveals that the boy is Siddhartha’s son and dies.</p><p>Siddhartha falls in love with his son, who, pampered by his mother and spoiled by luxury, hates and despises Siddhartha. This culminates in the boy running away to the city after stealing their money. Despite Vasudeva’s advice to let him be, Siddhartha goes to the city hoping to find him. Vasudeva follows and brings him back.</p><p>As days and months pass, Siddhartha misses his son terribly. He envies people with children, who love them and are loved in return. Once, he decides to go back to the city in the hope of seeing his son. But, when he looks at his reflection on the surface of the river, he sees his father’s face. He realizes that his father went through the same pain and suffering for him and he must suffer the same fate.</p><p>Siddhartha reveals all his thoughts and fears to the now old Vasudeva. Vasudeva takes him to the river. Here, Siddhartha finds peace and enlightenment looking at and listening to the river. He understands the oneness of everything, of people, of lives, of emotions and that time is not real. He discovers that Vasudeva knew this already, he was enlightened, he was God. Vasudeva then leaves for the forest into oneness.</p><p>Years pass and the old Siddhartha ferries old Govinda, who stays for a night in the hut. He asks Siddhartha about what he has learnt. Siddhartha says it can’t be taught or put into words. It comes from calmness, compassion, and regarding all things as being of value.</p><p>Govinda confesses that he has still not found peace. Siddhartha tells him that wisdom cannot be passed on, and it only comes from within. He talks about the deception of time. All things are in the state of nirvana and this is not possible to understand because of the illusion of time. Govinda can’t grasp the meaning of those words, but is desperate for enlightenment. Siddhartha asks him to kiss his forehead. As he bends near Siddhartha’s face, Govinda sees a wide range of images, visions, ranging from animals to God, simultaneously, all entangled and one. He feels enchanted and at peace with the experience, the vision under the surface of the exalted Siddhartha’s face.</p><p>Throughout the book, Siddhartha goes through a see-saw of emotions and perspectives. At one point, giving up all worldly possessions seems right to him. Later, he comes to enjoy all its beauties and joys. At one point, the behaviour, greed of humans seems trivial and their goals meaningless and shallow. Later, it all makes sense to him and he too behaves in the same way.</p><p>The philosophies in the book are debatable. Most people will find some of them agreeable and some others not. When Siddhartha explains that a stone is always everything including Budha and that it is not obvious because of the illusion of time, Govinda does not find sense in it. In fact, Siddhartha himself says that it will sound silly and foolish, because one person’s wisdom sounds like foolishness to another person. But Govinda also sees that Siddhartha’s manners and actions align with Gotama’s who is known to have attained nirvana. Yet, their teachings are different including their opinion on love. This could also mean that enlightenment and nirvana are just illusions. And Siddhartha and Gotama found peace with their own versions of it. While others were still searching.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82f96574376d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Lockdown Afternoon]]></title>
            <link>https://medium.com/the-creative-cafe/a-lockdown-afternoon-f5d44a3b25fc?source=rss-806d72b9e281------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5d44a3b25fc</guid>
            <category><![CDATA[flash-fiction]]></category>
            <category><![CDATA[fiction]]></category>
            <category><![CDATA[creative]]></category>
            <category><![CDATA[lockdown]]></category>
            <category><![CDATA[insanity]]></category>
            <dc:creator><![CDATA[Sandeep Rai]]></dc:creator>
            <pubDate>Wed, 09 Sep 2020 13:44:36 GMT</pubDate>
            <atom:updated>2020-09-09T13:44:36.057Z</atom:updated>
            <content:encoded><![CDATA[<p>For how long can you stay sane!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iUoKDraqu8bxHPiAreEMaA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@rodlong?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Rod Long</a> on <a href="https://unsplash.com/s/photos/covid-woman?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Lynn perched on the patio railing threatening to jump off. From the third floor.</p><p>Mark observed her from the living room smoking his pipe, releasing clouds of smoke.</p><p>‘Why does she do this when I know she is never going to do it,’ he wondered. He admired her balance though. He closed his eyes and let the smoke intoxicate him for a moment.</p><p>She screamed. It started with a high pitch, trailing off, and stopping abruptly.</p><p>He had to smile at the attempt. He looked at the patio. She was gone!</p><p>He shot out of his chair to where she was. He looked down, dreading what he may see.</p><p>She wasn’t there.</p><p>He took in some more smoke. The prankster. Where was she?</p><p>She climbed out from the neighbor’s patio that was connected to theirs.</p><p>‘You didn’t care about me.’ She stated.</p><p>‘But our neighbor did. He saved me. He took care of me. He was good.’ She moved closer. ‘Oh, he was so good.’ She said, biting her lips.</p><p>Mark looked in wonder. She was nuts.</p><p>‘Did you get high? Did your heart race?’ She mumbled crashing on the couch. ‘Smoke smoke everywhere. Not a drop of air to breathe. We should be dead already.’</p><p>‘Dead.’ She continued after a pause. ‘Like those smoke detectors you killed.’</p><p>He sat on the bean bag staring at the ceiling. As if on cue, their neighbor from upstairs decided to shake them up. It sounded as if a chase was on. The ceiling shook, so did the windows. It could easily have been an earthquake.</p><p>‘Why do they do this?’ She frowned.</p><p>Then, as if the spirit of a smoke detector got into her, she went off. She grabbed a tennis ball lying on the floor and hurled it repeatedly at the ceiling, pounding it. ‘Stop it, stop it!’ She roared.</p><p>It worked!</p><p>She stood triumphant, looking like a woman from the Stone Age furiously protecting her shelter from attack.</p><p>He watched in admiration. Lockdown had gotten to her. It had taken her back to her roots. To her raw instincts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5d44a3b25fc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-creative-cafe/a-lockdown-afternoon-f5d44a3b25fc">A Lockdown Afternoon</a> was originally published in <a href="https://medium.com/the-creative-cafe">the Cafe</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Ordinary Night]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/the-creative-cafe/an-ordinary-night-bf625d3054d7?source=rss-806d72b9e281------2"><img src="https://cdn-images-1.medium.com/max/1076/0*2ppFFMsy0z16cGDN" width="1076"></a></p><p class="medium-feed-snippet">There is nothing out of the ordinary in what I&#x2019;m about to tell you. This is very important to understand.</p><p class="medium-feed-link"><a href="https://medium.com/the-creative-cafe/an-ordinary-night-bf625d3054d7?source=rss-806d72b9e281------2">Continue reading on the Cafe »</a></p></div>]]></description>
            <link>https://medium.com/the-creative-cafe/an-ordinary-night-bf625d3054d7?source=rss-806d72b9e281------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf625d3054d7</guid>
            <category><![CDATA[creative]]></category>
            <category><![CDATA[night]]></category>
            <category><![CDATA[fiction]]></category>
            <category><![CDATA[sleepless]]></category>
            <category><![CDATA[spooky]]></category>
            <dc:creator><![CDATA[Sandeep Rai]]></dc:creator>
            <pubDate>Tue, 21 Jul 2020 23:47:10 GMT</pubDate>
            <atom:updated>2020-07-21T23:47:10.498Z</atom:updated>
        </item>
    </channel>
</rss>