<?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 Aaabhushan on Medium]]></title>
        <description><![CDATA[Stories by Aaabhushan on Medium]]></description>
        <link>https://medium.com/@aaabhushan10?source=rss-6ac4685bca08------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*UUOL6V6YPZRKxRnu</url>
            <title>Stories by Aaabhushan on Medium</title>
            <link>https://medium.com/@aaabhushan10?source=rss-6ac4685bca08------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 01:57:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aaabhushan10/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[Debugging Java OutOfMemoryError with Eclipse Memory Analyzer]]></title>
            <link>https://medium.com/@aaabhushan10/debugging-java-outofmemoryerror-with-eclipse-memory-analyzer-fb26502f2449?source=rss-6ac4685bca08------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb26502f2449</guid>
            <dc:creator><![CDATA[Aaabhushan]]></dc:creator>
            <pubDate>Tue, 17 Nov 2026 17:09:19 GMT</pubDate>
            <atom:updated>2026-11-17T17:09:19.732Z</atom:updated>
            <content:encoded><![CDATA[<p>As part of my journey toward becoming a better Java backend developer, I’ve been focusing on understanding some of the core concepts of Java beyond everyday application development.</p><p>One area I’m currently exploring is Java memory management, particularly OutOfMemoryError and memory leaks.</p><p>Java provides automatic memory management through its Garbage Collector (GC). At a high level, garbage collection relies on object reachability. When an object is no longer reachable from any GC root, it becomes eligible for garbage collection.</p><p>Some garbage collection algorithms use the mark-and-sweep approach, where the collector identifies reachable objects (marking) and reclaims unreachable ones (sweeping).</p><p>However, automatic memory management doesn’t mean Java applications are immune to memory leaks. Objects can remain reachable through references even when the application no longer needs them.</p><p>This can become particularly problematic in large enterprise applications, where services, collections, caches, and other objects may retain more memory than intended.</p><p>I wanted to understand how these issues happen, how to reproduce them, and more importantly, how to investigate them rather than simply guessing where the problem lies.</p><p>So, in this article, I’ll create a small Java program that intentionally retains objects, reproduce an OutOfMemoryError, generate a heap dump, and investigate it using Eclipse Memory Analyzer (MAT).</p><pre>import java.util.ArrayList;<br>import java.util.List;<br><br>public class MemoryLeakDemo {<br><br>    private static final List&lt;byte[]&gt; storage = new ArrayList&lt;&gt;();<br><br>    public static void main(String[] args) throws InterruptedException {<br><br>        System.out.println(&quot;Process ID: &quot; + ProcessHandle.current().pid());<br><br>        int count = 0;<br><br>        while (true) {<br>            storage.add(new byte[256 * 1024]);<br><br>            count++;<br><br>            if (count % 20 == 0) {<br>                System.out.println(&quot;Objects retained: &quot; + count);<br>            }<br><br>            Thread.sleep(250);<br>        }<br>    }<br>}</pre><p>The above is a simple program designed to demonstrate memory retention.</p><p>What is happening here is that we have an infinite loop (while (true)) that continuously creates a new byte[] object containing 256 KB of data in every iteration and adds its reference to the storage ArrayList.</p><p>Every 20 iterations, we print the number of objects added to the list so that we can observe how the number of retained objects increases over time.</p><p>But why is the Garbage Collector unable to clean up these objects?</p><p>The reason is object reachability.</p><p>The storage variable is a static field that references an ArrayList. This list maintains references to every byte array added to it.</p><p>As a result, even when the Garbage Collector runs, these byte arrays are still reachable through the reference chain originating from a GC root.</p><p>Therefore, they are not eligible for garbage collection.</p><p>As the loop continues, more byte arrays are created and retained, eventually exhausting the available Java heap memory and resulting in an OutOfMemoryError.</p><p>There are several ways we could address this problem, such as introducing a bounded collection or an appropriate eviction policy. However, the purpose of this experiment isn’t to fix the memory leak yet. I want to understand how to identify and investigate it.</p><h3>Reproducing the OutOfMemoryError</h3><p>Now that we understand what our program is doing, let’s see what happens when we limit the available heap memory.</p><p>First, we compile the program :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*IggcCqYrhgGIPYCJw-WjGQ.png" /></figure><p>Next, I ran the program with the initial heap size set to 32 MB and the maximum heap size set to 128 MB. This first run had no heap dump flag, just to observe the failure</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*4VndDPo2TYvf7SyN9_dFFA.png" /></figure><p>Then I ran it again with the same limits, this time adding JVM options so the JVM writes a heap dump when the OutOfMemoryError occurs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RrhiOVzJlF2QaxW9-eWdnw.png" /><figcaption>Screenshot of the command with the heap dump</figcaption></figure><p>As the program continues executing, the objects added to the list remain reachable. Therefore, the Garbage Collector cannot reclaim them. Eventually, the available heap memory is exhausted, and the JVM throws an OutOfMemoryError . This demonstrates how an application can exhaust its available heap memory when it continuously retains objects that are no longer needed.</p><p>So what I did to get the heap dump was using this following command :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yZ1erhslRqsYM-Mk7ZjC_Q.png" /></figure><p>Let’s break down the command:</p><ul><li><strong>-Xms32m</strong>: Sets the initial Java heap size to 32 MB.</li><li><strong>-Xmx128m</strong>: Sets the maximum Java heap size to 128 MB.</li><li><strong>-XX:+HeapDumpOnOutOfMemoryError</strong>: Tells the JVM to generate a heap dump when an OutOfMemoryError occurs.</li><li><strong>-XX:HeapDumpPath=./memory-leak.hpro</strong>f: Specifies where the heap dump should be saved. In this case, it is saved as memory-leak.hprof in the current directory.</li><li><strong>MemoryLeakDemo</strong>: The Java class we want to execute.</li></ul><p>So, essentially, I am running the same Java program again, but this time I’ve added JVM options to generate a heap dump automatically when an OutOfMemoryError occurs. This gives me a snapshot of the objects in the heap that I can investigate to understand where the memory is being retained.</p><p>Now that we have generated the heap dump, the next step is to investigate it using Eclipse Memory Analyzer (MAT). Rather than guessing which objects are consuming memory, we’ll use MAT to examine the heap and understand which objects are retaining the most memory and why they remain reachable.</p><p>Before opening it in MAT, let’s first verify that the heap dump was successfully generated.</p><p>We can do this using the following command:</p><pre>ls -lh memory-leak.hprof</pre><p>The command displays the file’s size and other details. In my case, the generated heap dump was approximately 99 MB.</p><p>Its screenshot is :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*TudRu_fFys4-4YE5JBKQdg.png" /></figure><p>Here are the following commands to run to replicate this :</p><pre>javac MemoryLeakDemo.java<br>java -Xms32m -Xmx128m MemoryLeakDemo<br>java -Xms32m -Xmx128m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=./memory-leak.hprof MemoryLeakDemo<br>ls -lh memory-leak.hprof</pre><p>Now that we have verified that the heap dump was successfully generated, let’s open it using Eclipse Memory Analyzer (MAT).</p><p>I’ll launch MAT and open the memory-leak.hprof file that we generated earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YrN_KFh3iIK-vhuADwdKOw.png" /><figcaption>Initial Heap dump diagram</figcaption></figure><p>Once the heap dump is loaded, Eclipse Memory Analyzer provides several tools to investigate the objects in the Java heap. To get an initial understanding of what might be causing the memory issue, let’s start by generating the Leak Suspects Report.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4cu-sfu7l8UTB9LY7JQSZw.png" /><figcaption>Leak Suspect Report</figcaption></figure><h3>Understanding the Leak Suspects Report</h3><p>After generating the Leak Suspects Report, MAT identifies one instance of java.util.ArrayList that is retaining approximately 99.9 MB of memory, accounting for 98.94% of the reported heap.</p><p>Looking at the top consumers, we can see that 381 instances of byte[] account for almost all of this memory.</p><p>This immediately caught my attention because it matches what we implemented in our program:</p><pre>storage.add(new byte[256 * 1024]);</pre><p>Remember, every iteration creates a new byte array of 256 KB and adds it to the storage list.</p><p>MAT also identifies an internal java.lang.Object[] instance. This makes sense because an ArrayList internally uses an object array to store references to its elements.</p><p>So, based on the report, we can already see that our ArrayList is retaining almost all the memory occupied by the byte arrays.</p><p>However, this report only gives us an overview of the suspected memory retention. I also want to understand exactly how these objects are connected and why they remain reachable.</p><p>For that, let’s investigate the Dominator Tree and the Path to GC Roots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qpp1EKpuRbHG2SUHCI2QFQ.png" /><figcaption>Screenshot of the Dominator Tree</figcaption></figure><h3>Investigating the Dominator Tree</h3><p>If we look at the Dominator Tree, we can see that the ArrayList is retaining almost 99.9 MB of memory.</p><p>What’s interesting here is the difference between its shallow heap and retained heap.</p><p>The shallow heap of the ArrayList is only 24 bytes, whereas its retained heap is 99,885,200 bytes.</p><p>The reason for this difference is that the ArrayList holds references to other objects, including its internal Object[], which in turn holds references to the byte arrays.</p><p>So, even though the ArrayList itself occupies very little memory, it dominates a much larger object graph.</p><p>This also explains why simply looking at the shallow heap of an object isn’t always enough when investigating memory issues.</p><h3>Investigating the Path to GC Roots</h3><p>After looking at the Dominator Tree, I wanted to understand why the ArrayList was still reachable and what references were keeping it alive.</p><p>For this, I used MAT’s <strong>Path to GC Roots</strong> feature.</p><p>The result shows two references to the same ArrayList:</p><ul><li>A local reference associated with the main thread.</li><li>The static storage field in the MemoryLeakDemo class.</li></ul><p>This helps us understand why the objects are not being garbage collected.</p><p>The static storage field references the ArrayList, which internally holds references to its backing Object[]. That array, in turn, holds references to the 381 byte[] objects.</p><p>As a result, these byte arrays remain reachable and cannot be reclaimed by the Garbage Collector.</p><p>This investigation helped me connect what I saw in the Leak Suspects Report and Dominator Tree with the actual reference chain keeping the objects alive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JrNvi9KJwRpYbA1xFUvdZA.png" /><figcaption>Path to GC Roots</figcaption></figure><p>So how to fix this ?</p><p>We can’t set storage to null because it’s static final, and calling storage.clear() only delays the crash, because the loop immediately starts refilling it. A real fix has to decide which objects are worth keeping and let the rest go.</p><p>In this example, suppose we only ever need the 50 most recent byte arrays. An ArrayDeque with an explicit size limit can do exactly that: once it reaches 50 entries, each new array pushes the oldest one out.</p><pre>import java.util.ArrayDeque;<br>import java.util.Deque;<br><br>public class MemoryLeakFixed {<br><br>    private static final int MAX_RETAINED = 50;<br>    private static final Deque&lt;byte[]&gt; storage = new ArrayDeque&lt;&gt;();<br><br>    public static void main(String[] args) throws InterruptedException {<br><br>        System.out.println(&quot;Process ID: &quot; + ProcessHandle.current().pid());<br><br>        int count = 0;<br><br>        while (true) {<br>            storage.addLast(new byte[256 * 1024]);<br><br>            if (storage.size() &gt; MAX_RETAINED) {<br>                storage.removeFirst(); // drop the oldest reference<br>            }<br><br>            count++;<br><br>            if (count % 20 == 0) {<br>                System.out.println(&quot;Objects created: &quot; + count<br>                        + &quot; | currently retained: &quot; + storage.size());<br>            }<br><br>            Thread.sleep(250);<br>        }<br>    }<br>}</pre><p>The storage field is still static, so it is still a GC root. What changed is how much it points to. When removeFirst() runs, the oldest byte[] has no references left, so the Garbage Collector can reclaim it.</p><p><strong>Verifying the fix</strong></p><p>I ran it with the same heap limits as before:</p><pre>javac MemoryLeakFixed.java<br>java -Xms32m -Xmx128m MemoryLeakFixed</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kqiPPydrcjFHtD9-GpW4LQ.png" /></figure><p>This time the program ran well past the 380 objects where the leaky version crashed. “Objects created” keeps climbing while “currently retained” stays at 50.</p><p>To confirm this in MAT, I took a heap dump from the running process, using the process ID the program printed (11768 in my run):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aA6mhAzSOLbLJby3rsao8g.png" /></figure><pre>jcmd 11768 GC.heap_dump ./memory-fixed.hprof</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rj3JeVQJtgPAwZkqglIsEA.png" /><figcaption>Screenshot of the fixed class’s dominator tree</figcaption></figure><p>In the Dominator Tree, the biggest entry is now the MemoryLeakFixed class, retaining 13,111,352 bytes (about 13.1 MB), or 92.42% of the heap. MAT lists the class rather than the deque because a static field belongs to the class. The whole heap is about 14.2 MB, compared with roughly 101 MB in the leaky version.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BBH4HajySs2SH9p-8ztfqg.png" /><figcaption>Screenshot of path to GC Roots</figcaption></figure><p>Running Path to GC Roots on the ArrayDeque shows it retaining 13,108,336 bytes, reachable through a single path: the static storage field. That matches the code, since 50 arrays of 256 KB come to 13,107,200 bytes, and the rest is object overhead. The static field is still the root, but it now holds a fixed 50 arrays instead of an ever-growing list.</p><p><strong>In real applications</strong></p><p>You will rarely see a raw byte[] list. The same pattern usually appears as an unbounded cache, a static Map that only grows, or listeners that are registered but never removed. The fix is the same idea: put a limit or an eviction rule on whatever the long-lived reference points to. In a real service, that would typically be a cache library with a maximum size or expiry time (Caffeine, for example) instead of a hand-written deque.</p><p>Although this example is relatively simple, it helped me understand the fundamentals of investigating memory-retention issues. In real-world enterprise applications, the situation can be considerably more complicated. Objects may be retained through multiple layers of references involving caches, collections, services, static fields, and other application components. This is where tools like Eclipse Memory Analyzer become particularly useful. Instead of manually tracing thousands of objects and references, we can use the Dominator Tree, Leak Suspects Report, and Path to GC Roots to narrow down the investigation and identify potential causes of memory retention.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb26502f2449" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CTEs in PostgreSQL: Performance, Pitfalls, and Best Practices]]></title>
            <link>https://medium.com/@aaabhushan10/ctes-in-postgresql-performance-pitfalls-and-best-practices-bb4b3af28b80?source=rss-6ac4685bca08------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb4b3af28b80</guid>
            <category><![CDATA[query-optimization]]></category>
            <category><![CDATA[sql-queries]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Aaabhushan]]></dc:creator>
            <pubDate>Tue, 09 Dec 2025 08:32:27 GMT</pubDate>
            <atom:updated>2025-12-09T14:57:57.793Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to Common Table Expressions (CTEs)</h3><p>So , I have been using PostgreSQL database functions for the development of dashboard apis or report sections apis. I mainly use them for the apis that are used in charts since those are the one that need the most amount of calculation .So, instead of doing calculations in java I primarily do it in database since they are faster than using normal java . So,when trying to use them to create dashboard apis in my current job, I came across a new term : ”Common Table Expressions”.So first of all ,what are CTEs? They are query that is specific to query that is mainly used to increase readability and sometimes even make it faster . So let’s take an example of a simple PostgreSQL function that does not use CTEs :</p><pre>CREATE OR REPLACE FUNCTION orders_pipeline(<br>    customer_id BIGINT<br>) <br>RETURNS TABLE (<br>    metric_name VARCHAR,<br>    metric_value BIGINT,<br>    metric_percentage NUMERIC<br>) AS $$<br>BEGIN<br>    RETURN QUERY<br>    SELECT <br>        m.m_name AS metric_name,<br>        m.m_value AS metric_value,<br>        ROUND(m.m_value::NUMERIC / t.total * 100, 2) AS metric_percentage<br>    FROM (<br>        SELECT <br>            COUNT(*) AS total,<br>            COUNT(*) FILTER (WHERE o.status = &#39;PENDING&#39;) AS pending,<br>            COUNT(*) FILTER (WHERE o.status = &#39;SHIPPED&#39;) AS shipped,<br>            COUNT(*) FILTER (WHERE o.status = &#39;DELIVERED&#39;) AS delivered,<br>            COUNT(*) FILTER (WHERE o.status = &#39;CANCELLED&#39;) AS cancelled<br>        FROM orders o<br>        JOIN customers c ON o.customer_id = c.id<br>        WHERE c.id = customer_id<br>    ) AS t<br>    CROSS JOIN LATERAL (<br>        VALUES<br>            (&#39;cancelledOrders&#39;, t.cancelled),<br>            (&#39;pendingOrders&#39;, t.pending),<br>            (&#39;shippedOrders&#39;, t.shipped),<br>            (&#39;deliveredOrders&#39;, t.delivered)<br>    ) AS m(m_name, m_value);<br>END;<br>$$<br>LANGUAGE plpgsql STABLE;</pre><p>This is a function that does not use CTE ,so it is harder to read and harder to maintain .The reason why it is bad is due to many reasons . It is harder to read is that it is :</p><ul><li>A single giant nested SELECT</li><li>Harder to debug</li><li>Easy to make mistakes</li><li>Hard to extend (e.g., adding new metrics later)</li></ul><p>So let’s add CTE in here and the query becomes like this :</p><pre>CREATE OR REPLACE FUNCTION orders_pipeline(<br>    customer_id BIGINT<br>) <br>RETURNS TABLE (<br>    metric_name VARCHAR,<br>    metric_value BIGINT,<br>    metric_percentage NUMERIC<br>) AS $$<br>BEGIN<br>    RETURN QUERY<br>    WITH base AS (<br>        SELECT<br>            o.status,<br>            o.id AS order_id,<br>            c.id AS customer_id<br>        FROM orders o<br>        JOIN customers c ON o.customer_id = c.id<br>        WHERE c.id = customer_id<br>    ),<br>    total AS (<br>        SELECT <br>            COUNT(*) AS total,<br>            COUNT(*) FILTER (WHERE status = &#39;PENDING&#39;) AS pending,<br>            COUNT(*) FILTER (WHERE status = &#39;SHIPPED&#39;) AS shipped,<br>            COUNT(*) FILTER (WHERE status = &#39;DELIVERED&#39;) AS delivered,<br>            COUNT(*) FILTER (WHERE status = &#39;CANCELLED&#39;) AS cancelled<br>        FROM base<br>    )<br>    SELECT <br>        m.m_name AS metric_name,<br>        m.m_value AS metric_value,<br>        ROUND(m.m_value::NUMERIC / t.total * 100, 2) AS metric_percentage<br>    FROM total t<br>    CROSS JOIN LATERAL (<br>        VALUES<br>            (&#39;cancelledOrders&#39;, cancelled),<br>            (&#39;pendingOrders&#39;, pending),<br>            (&#39;shippedOrders&#39;, shipped),<br>            (&#39;deliveredOrders&#39;, delivered)<br>    ) AS m(m_name, m_value);<br>END;<br>$$<br>LANGUAGE plpgsql STABLE;</pre><p>So in the above query ,it is better than the previous query due to the following reasons which are :</p><ol><li>Clear separation of concerns: the base CTE contains all orders for the given customer, the total CTE aggregates counts from base, and the final SELECT uses these totals.</li><li>Avoid repeating the joins : With CTE, we only define the expensive join once .</li><li>Aggregation becomes much cleaner with CTE : With CTE, the query is simple and readable :</li></ol><pre>total AS (<br>  SELECT COUNT(*) ... FROM base<br>)</pre><p>Without it we must need to nest the Joins directly inside the aggregation, which becomes bulky and hard to read .</p><p>4. Query becomes more maintainable with CTE : If tomorrow we add a new metric :</p><p>With CTE -&gt; modify only the total block</p><p>Without CTE -&gt; modify the big nested sub query</p><h3><strong>When can CTEs be slower ?</strong></h3><p>CTEs are not always better . There is a high chance that they may make your query slower as well .Here may be some of the reasons that they make the query slower :</p><ol><li>When it is materialized unnecessarily</li><li>When it is referenced multiple times and recomputed.</li><li>When it produces a large intermediate result.</li></ol><pre>WITH cte AS (<br>  SELECT * FROM orders<br>)<br>SELECT * FROM cte WHERE amount &gt; 1000;</pre><p>This is a simple but classic example of when a CTE can be slower than a normal select query. Instead of directly fetching a filtered select query, we instead use CTE to fetch all of the data from the orders table and then only we filter and this is making the query slower compared to normal select query.</p><h3>Balancing when to use it and when to not use it :</h3><p>We mainly use CTE to maintain readability and main complexity of the query, when multiple part of the query use the same filtered query ,when we need staged transformation . We should mainly avoid using CTE around simple sub queries since it may hamper performance and make it harder to read by the other developers . We should also check the performance using EXPLAIN ANALYZE keyword given to us by PostgreSQL .</p><h3>Conclusion</h3><p>CTEs are one of the most powerful tools in PostgreSQL for organizing complex queries. While they don’t make everything faster, they help developers a cleaner ,more structured way to build SQL pipelines-especially in dashboards , analytics queries and reporting APIs.But,we must avoid them if we need only need a small inline subquery. Like everything in SQL, the goal is to use EXPLAIN ANALYZE to measure performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb4b3af28b80" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>