<?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 Bhagirath on Medium]]></title>
        <description><![CDATA[Stories by Bhagirath on Medium]]></description>
        <link>https://medium.com/@bgollako?source=rss-9533d3a3334e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*HYybqoAwinUqe7_G</url>
            <title>Stories by Bhagirath on Medium</title>
            <link>https://medium.com/@bgollako?source=rss-9533d3a3334e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 00:02:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bgollako/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[The Phantom NullPointerException]]></title>
            <link>https://medium.com/@bgollako/the-phantom-nullpointerexception-0aad3dff1dd5?source=rss-9533d3a3334e------2</link>
            <guid isPermaLink="false">https://medium.com/p/0aad3dff1dd5</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[arm64]]></category>
            <category><![CDATA[x86]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Bhagirath]]></dc:creator>
            <pubDate>Thu, 01 Oct 2026 14:12:50 GMT</pubDate>
            <atom:updated>2026-10-01T14:32:59.803Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine taking a perfectly good, battle-tested Java application that has run flawlessly for years. You drop it onto a shiny new ARM64 server — maybe an AWS Graviton instance to save on compute costs — and suddenly, it starts throwing bizarre NullPointerException errors.</p><p>You haven’t changed a single line of code. The JDK version is exactly the same. So, what gives?</p><h3>The Impossible Crash</h3><p>We began observing a spate of NullPointerException (NPE) errors in our services shortly after migrating our servers from x86 to ARM64 . The stack trace pointed deep inside the standard Java library:</p><pre>Caused by: java.lang.NullPointerException: Cannot invoke &quot;java.util.HashMap.containsKey(Object)&quot; because &quot;this.map&quot; is null<br>    at java.util.HashSet.contains(HashSet.java:205)<br>    at com.acme.api.ratelimit.RateLimitService.applyTrafficRules(RateLimitService.java:255)<br>    at com.acme.api.ratelimit.RateLimitService.enforceLimits(RateLimitService.java:155)<br>    at com.acme.api.ratelimit.RateLimitService.inspectRequest(RateLimitService.java:92)<br>    at com.acme.api.ratelimit.TrafficController.handle(TrafficController.java:103)</pre><p>Read that error carefully. It doesn’t say the HashSet itself was null. The crash happened inside the .contains() method in the standard library. It says the internal map field belonging to the HashSet was null.</p><p>HashSet is a thin wrapper around a HashMap:</p><pre>public class HashSet&lt;E&gt; {<br>    private transient HashMap&lt;E,Object&gt; map;   // &lt;-- &quot;this.map&quot;<br><br>    public HashSet() {<br>        map = new HashMap&lt;&gt;();                 // assigned in the constructor<br>    }<br><br>    public boolean contains(Object o) {<br>        return map.containsKey(o);             // line 205 -- NPE if map is null<br>    }<br>}</pre><p>map is assigned in the constructor. A fully constructed HashSet always has a non-null map. So seeing map == null means we are looking at a HashSet that is <em>not finished being built yet</em> — a half-created object.</p><p>How can another thread ever see a half-created object? That is the whole bug.</p><h3>The Innocent-Looking Culprit</h3><p>We traced the half-baked object back to a data model used for rate limiting rules. It used a classic “lazy initialization” pattern:</p><pre>private Set&lt;String&gt; blockedIps; <br><br>public Set&lt;String&gt; getBlockedIps() {<br>    if (blockedIps == null) {                <br>        blockedIps = new HashSet&lt;String&gt;();  <br>    }<br>    return blockedIps;<br>}</pre><p>This looks completely harmless, right? Don’t build the set until someone asks for it. It saves memory!</p><p>In a single-threaded world, this is fine. But when multiple threads share this object, it becomes a ticking time bomb known as <strong>unsafe publication</strong>.</p><p>Here is the secret: that single line of Java (blockedIps = new HashSet&lt;String&gt;();) is actually <em>two</em> separate writes to memory at the machine level:</p><ul><li><strong>Write A:</strong> Build the internal HashMap inside the constructor.</li><li><strong>Write B:</strong> Assign the memory address of this new object to the blockedIps variable.</li></ul><p>Logically, Write A has to happen before Write B. And for the thread doing the work, it always does. But here is the catch: <strong>the CPU does not guarantee that other threads will see those writes in that order.</strong></p><h3>Why other threads can see them out of order</h3><p>To understand why, we have to look at the how ordering of writes matters.</p><p>CPUs are blazingly fast — much faster than main memory. To avoid waiting around, when a CPU core wants to write data, it doesn’t write directly to the shared RAM. Instead, it tosses the write into a tiny, per-core queue called a <strong>store buffer</strong>, and then instantly moves on to its next task. The buffer eventually drains out to the shared cache in the background.</p><p>Write A (the map) and Write B (the reference variable) go into this store buffer. Because they are writing to completely different areas of memory, they can drain out of the buffer and become visible to other threads in the opposite order.</p><ol><li><strong>Thread 1</strong> triggers the lazy init. Write A and Write B go into the store buffer.</li><li>The store buffer decides to drain Write B (the variable assignment) to shared memory <em>first</em>.</li><li><strong>Thread 2</strong> comes along, calls getBlockedIps(), and sees that blockedIps is no longer null! It grabs the memory address and immediately calls .contains().</li><li>But Write A hasn’t drained yet. Thread 2 looks inside the object, finds an empty void where the map should be, and <strong>BOOM</strong>. NullPointerException.</li></ol><h3>The Tale of Two Architectures</h3><p>So, why did this exact same code run flawlessly for years, only to crash the moment it touched an ARM processor?</p><p>It all comes down to the hardware’s “Memory Model” — the strictness of the rules governing those store buffers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uicyn6CZ4H0Kj8Qr6Mmiig.png" /></figure><h4>x86 (Intel/AMD)</h4><p>The x86 architecture uses a memory model called <strong>Total Store Order (TSO)</strong>. It physically forces the store buffer to drain writes in the exact order they were issued by the program. On x86, it is physically impossible for Write B to become visible before Write A.</p><h4>ARM64 (Graviton/Apple Silicon)</h4><p>The ARM architecture (AArch64) uses a <strong>Weakly Ordered</strong> memory model. ARM is all about maximum throughput and power efficiency. It doesn’t care about the order of the line. The hardware routinely lets store buffers drain out of order if it speeds things up.</p><h3>The Fix</h3><p>To fix this, we had two choices.</p><p><strong>Option 1: Double-Checked Locking.</strong> You can make the blockedIps field volatile and wrap the initialization in a synchronized block. Since Java 5 (JSR-133), a volatile field prevents the CPU and compiler from reordering those writes</p><p><strong>Option 2: Eager Initialization (Our choice).</strong> Just build the thing up front! Needless to say</p><pre>// FIXED: Built instantly in the constructor!<br>private Set&lt;String&gt; blockedIps = new HashSet&lt;&gt;();</pre><h3>The Takeaway</h3><p>The assumption of hardware-agnostic execution is demonstrably flawed in the context of highly concurrent systems. As the enterprise ecosystem accelerates its transition to ARM64 architectures to capitalize on superior compute density and cost efficiency, applications are losing the inherent architectural protections provided by the x86 Total Store Order memory model. The scale of this transition is massive: ARM architecture now accounts for over 50% of the hyperscale cloud computing market, with more than 14% of all cloud virtual machines currently running on ARM processors. The financial incentives driving this shift are equally substantial. For instance, AWS Graviton instances deliver up to 40% better price-performance, cost up to 20% less, and consume up to 60% less energy than comparable x86 hardware. Heavy data workloads, such as Apache Spark on Graviton, have demonstrated up to a 27% overall improvement in price-performance.</p><p>Migrating legacy workloads to these highly efficient but weakly ordered architectures requires a rigorous audit of concurrent data structures. Engineering teams must systematically eliminate unsynchronized lazy initialization patterns, enforce strict adherence to the Java Memory Model’s barrier semantics, and recognize that empirical validation on strongly ordered processors is fundamentally insufficient for proving thread safety.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0aad3dff1dd5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing performance with Go’s iterators]]></title>
            <link>https://medium.com/@bgollako/enhancing-performance-with-gos-iterators-d2974ddeb7e1?source=rss-9533d3a3334e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2974ddeb7e1</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[iterators]]></category>
            <dc:creator><![CDATA[Bhagirath]]></dc:creator>
            <pubDate>Wed, 16 Jul 2025 20:17:11 GMT</pubDate>
            <atom:updated>2025-07-16T21:15:37.005Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MBTJ0MAQSbSNSZBqHLp61g.jpeg" /></figure><p>At our company, we primarily use Go to build micro services that interface directly with our network devices using protocols like NETCONF, TR-069, STUN etc. We chose Go for several compelling reasons: its fast startup time, efficient concurrency model powered by lightweight go routines, excellent I/O performance, and overall ease of development.</p><p>Because these services are device-facing, high availability and low latency are critical. Any performance bottlenecks can have cascading effects on downstream systems, potentially impacting the entire service pipeline. Hence, we are constantly exploring new strategies and features to enhance the speed and efficiency of these micro services.</p><p>We ran into on such improvement when going through the seemingly innocuous iterator package added in Go 1.23. Little did we know, this little jaunt down the rabbit hole would result in massive improvements in latency for our services.</p><p>We make extensive use of Go routines across our codebase to enhance performance and reduce execution time. One particularly common pattern involves breaking down large messages into smaller chunks and parsing them individually.</p><p>In the example below, we use a chunk function to split a large message into multiple smaller parts, which are then sent over a channel. This approach allows us to handle large payloads efficiently and is a recurring pattern in many of our services.</p><pre>// The below function breaks down the given msg into smaller chunks<br>// and returns them over a channel<br>func chunk(msg []byte) &lt;- chan []byte {<br>  ch := make(chan int, some_size)<br>  go func() {<br>    defer close(ch)<br>    // split msg into smaller chunks<br>    // and return them over ch<br>  }()<br>  return ch<br>}<br><br>....<br>if len(msg) &gt; limit {<br>  go func() {<br>    // Call the above chunk function using the for range construct<br>    for data := range chunk(msg) {<br>      // do what is needed with the data<br>    }<br>  }()<br>}</pre><p>We decided to replace the above <em>chunk</em> function with an iterator as shown below.</p><pre>// The below function breaks down the given msg into smaller chunks<br>// and returns them over a channel<br>func chunk(msg []byte) iter.Seq[[]byte] {<br>  return func(yield func(V []byte) bool) {<br>    // yield the chunks<br>  }<br>}<br><br>....<br>if len(msg) &gt; limit {<br>  go func() {<br>    // Call the above chunk function using the for range construct<br>    for data := range chunk(msg) {<br>      // do what is needed with the data<br>    }<br>  }()<br>}</pre><p>Upon benchmarking the code, we noticed a 33% improvement in performance and a 6 % improvement in memory consumed :).</p><h3>Coroutines in Go</h3><p>Turns out iterators use co routines under the hood to switch between both the functions, with only one function being executed at one time providing concurrency without parallelism.</p><p><a href="https://github.com/golang/go/blob/master/src/runtime/coro.go">go/src/runtime/coro.go at master · golang/go</a></p><p>Context switching performance varies significantly across different concurrency models. Coroutine switches, for instance, are extremely lightweight, typically taking around 10 nanoseconds. In contrast, Go routine switches, managed by the Go scheduler, take a few hundred nanoseconds. Meanwhile, context switches between OS threads are even more expensive, often taking several microseconds. This performance gap partly explains why Java’s traditional threading model is considered heavier compared to Go’s lightweight concurrency. However, Java has recently addressed this with the introduction of virtual threads, which aim to bring go routine-like efficiency to the JVM.</p><p>Curious about how these differences translate into real-world performance, we decided to benchmark a few common iteration patterns. Specifically, we compared the performance of custom iterators, for range over channels, and the standard for loop using a simple task: computing the sum of the first million natural numbers.</p><pre>func NormalLoop() {<br> sum := 0<br> for n := range 1000_000 {<br>  sum += n<br> }<br> fmt.Println(sum)<br>}<br><br>func IteratorForN() {<br> sum := 0<br> for n := range Ints(1000_000) {<br>  sum += n<br> }<br> fmt.Println(sum)<br>}<br><br>func IterateWithRoutines() {<br> sum := 0<br> for n := range IntsOverCh(1000_000) {<br>  sum += n<br> }<br> fmt.Println(sum)<br>}<br><br>func IntsOverCh(n int) &lt;-chan int {<br> ch := make(chan int, 1000_000)<br> go func() {<br>  defer close(ch)<br>  for i := 0; i &lt; n; i++ {<br>   ch &lt;- n<br>  }<br> }()<br> return ch<br>}<br><br>func Ints(n int) iter.Seq[int] {<br> return func(yield func(int) bool) {<br>  for i := 0; i &lt; n; i++ {<br>   if !yield(i) {<br>    return<br>   }<br>  }<br> }<br>}</pre><p>We observed the following bench marks, with iterators far out performing <br>for range over channels<em>,</em> with their performance coming close to the normal standard for loop !!!.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6XbitdtOBy4w2hM02Bu90Q.png" /></figure><h3><strong>References</strong></h3><p><a href="https://research.swtch.com/coro">https://research.swtch.com/coro</a><br><a href="https://go.dev/src/runtime/coro.go">https://go.dev/src/runtime/coro.go</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2974ddeb7e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>