<?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 Bhavya Joshi on Medium]]></title>
        <description><![CDATA[Stories by Bhavya Joshi on Medium]]></description>
        <link>https://medium.com/@bhavya.joshi1901?source=rss-7bec68e3439e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Qgv6oCdMglrTOfc-</url>
            <title>Stories by Bhavya Joshi on Medium</title>
            <link>https://medium.com/@bhavya.joshi1901?source=rss-7bec68e3439e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 17:21:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bhavya.joshi1901/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[From Heap to Off-Heap: Revolutionizing Big Data Processing with Java FFM]]></title>
            <link>https://medium.com/@bhavya.joshi1901/from-heap-to-off-heap-revolutionizing-big-data-processing-with-java-ffm-3bdb60ac4252?source=rss-7bec68e3439e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bdb60ac4252</guid>
            <category><![CDATA[file-format]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[apache]]></category>
            <dc:creator><![CDATA[Bhavya Joshi]]></dc:creator>
            <pubDate>Fri, 24 Oct 2025 07:45:35 GMT</pubDate>
            <atom:updated>2025-10-24T12:54:10.133Z</atom:updated>
            <content:encoded><![CDATA[<h3>From On-Heap to Off-Heap: Revolutionizing Big Data Processing with Java FFM</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fc4YR4x125bnu8ktS-MuWA.png" /><figcaption>Figure 1 : Gemini Generated Image representing DataFlow using MMIO and FFM</figcaption></figure><p>For years, Java developers working with big data have battled one constant challenge — the <strong>heap</strong>. Garbage Collection (GC) pauses, object overhead, and unpredictable memory churn often throttle performance, especially when dealing with multi-gigabyte datasets. While frameworks like Apache Spark and Arrow have pushed the boundaries of in-memory analytics, most Java applications still live within the confines of the managed heap.</p><p>But what if you could break free?</p><p>With the <strong>Foreign Function &amp; Memory (FFM) API</strong> introduced in modern Java (from JDK 22 onward), developers can now allocate and manipulate memory <strong>off the heap</strong>, safely and efficiently — without JNI complexity or unsafe hacks. This opens the door to <strong>high-performance, zero-copy data pipelines</strong> that rival native C++ systems.</p><p>In this article, we’ll explore how to harness Java FFM for <strong>memory-mapped I/O</strong> — reading large datasets directly into <strong>off-heap memory</strong> and integrating them seamlessly with <strong>Apache Arrow’s columnar memory model</strong>. The result?<br> Blazing-fast data access, minimal GC pressure, and performance that scales effortlessly across modern CPUs.</p><p>By the end, you’ll see how moving data “off the heap” isn’t just an optimization — it’s a paradigm shift for how we think about big data processing in Java.</p><h3>The Problem with Traditional I/O</h3><p>In most Java applications, file reading is still dominated by the same old players — BufferedReader, InputStream, or FileChannel. While these APIs are robust and convenient, they all share one bottleneck:<br> <strong>every byte must pass through the Java heap.</strong></p><p>When dealing with small files, this isn’t an issue. But in the world of big data — gigabytes or even terabytes of CSVs, Parquet files, or logs — this approach becomes painfully inefficient. Each read operation triggers memory allocations, string conversions, and eventually, garbage collection cycles that disrupt throughput.</p><p>As datasets scale, the JVM starts spending more time managing memory than processing data.</p><p>This is why high-performance systems like Spark, Arrow, and ClickHouse moved toward <strong>off-heap, columnar memory layouts</strong> long ago. Yet for regular Java developers, working with off-heap memory used to mean diving into unsafe code, JNI, or complex native bindings — until now.</p><h3>What Is Memory-Mapped I/O?</h3><p>At its core, <strong>memory-mapped I/O (MMIO)</strong> is a technique that lets you treat files as if they were <strong>part of your program’s memory</strong>.<br> Instead of reading bytes into buffers with explicit I/O calls, the operating system maps the file’s contents directly into your process’s address space.</p><p>That means when you access a particular byte in memory, you’re effectively accessing that byte <em>in the file itself</em> — no copying, no buffering, no user-space overhead.</p><p>Imagine your 10 GB CSV file isn’t something you “read” line by line, but rather something that just <em>exists</em> in memory, and you can randomly access any part of it instantly. That’s the power of memory mapping.</p><p>Under the hood, the OS handles paging automatically — it loads parts of the file into RAM only when needed, and swaps them out when they’re not. This allows your application to work with files much larger than physical memory, with near-zero latency compared to traditional file reads.</p><h3>Enter the Java Foreign Function &amp; Memory (FFM) API</h3><p>Starting with JDK 22, the <strong>FFM API</strong> became production-ready, giving Java developers first-class tools to work directly with native memory.<br> It provides a <strong>safe and ergonomic</strong> way to:</p><ul><li>Allocate memory segments outside the Java heap</li><li>Access and manipulate data using native layouts</li><li>Map files directly into memory for zero-copy reads</li><li>Interoperate with native libraries — without JNI</li></ul><p>In essence, FFM bridges the gap between Java’s managed runtime and the raw performance of systems programming.</p><p>For more information about I/O mechanisms :<a href="https://www.geeksforgeeks.org/computer-organization-architecture/memory-mapped-i-o-and-isolated-i-o/"> MMIO and II/O</a></p><h3>From Memory Mapping to Vectorized Processing</h3><p>Once data lives off-heap, the next question is: <em>how do we process it efficiently?</em></p><p>That’s where <strong>Apache Arrow</strong> comes in. Arrow defines a standard in-memory columnar format that enables zero-copy data exchange between languages and systems.<br> By using Arrow’s <strong>VectorSchemaRoot</strong> in conjunction with Java FFM, you can parse memory-mapped data directly into column vectors stored in off-heap memory.</p><p>This allows Java to compete head-to-head with native systems like C++ and Rust in terms of throughput — all while staying fully within the JVM ecosystem.</p><p>In the next section, we’ll walk through the actual implementation — showing how to:</p><ul><li>Memory-map a large file using FFM</li><li>Read it into an off-heap <strong>MemorySegment</strong></li><li>Build Arrow vectors from native memory</li><li>Benchmark it against traditional heap-based readers</li></ul><p>Alright, enough talk — let’s put in some work!</p><h3>Implementation</h3><p>I will only be showing snippets of implementation. For entire codebase, please go through the repository : <a href="https://github.com/Bhavya1119/Java-FFM-MMIO">Github Repo</a></p><h4>1. Foundation: Memory Management</h4><p>I developed a wrapper class to handle memory operations. At its core:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*AuoPL2gMrZoHAxUDMSMnwQ.png" /></figure><p>Here you will encounter Arena object .</p><p>An <strong>Arena</strong> in Java FFM (Foreign Function &amp; Memory API) is a <strong>lifetime manager</strong> for memory segments. It decides <strong>how long off-heap memory stays valid</strong> and <strong>when it should be released</strong>.</p><ul><li><strong>Arena.ofConfined()</strong> → creates a private arena tied to the current thread.<br> Memory allocated in it is <strong>automatically freed when the arena is closed</strong> (like a scoped resource).</li></ul><p>For more details on Arena and FFM API : <a href="https://docs.oracle.com/en/java/javase/21/core/foreign-function-and-memory-api.html">FFM Docs</a></p><p>We are using a <strong>FileChannel </strong>object to open and map data bytes directly to memory segments and finally return our wrapper object.</p><h3>2. Contract: Reader Interface</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*pC1Jha9aPaZnRQyDwazuKg.png" /></figure><p>A reader interface for supporting other fileformats aswell.</p><h3>3. Schema Definition</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*TOcfgzM64Xqoo4qJWqRwGA.png" /></figure><p>Immutable container holding inferred schema metadata.</p><h3>4. Smart Type Detection</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*k8QKxIxYLO-XJ2eLu83PXg.png" /></figure><p>Samples first N (10) rows to statistically determine column data types. Avoids manual schema definition — automatically detects INT, DOUBLE, DATE, etc.</p><h3>5. Statistical Type Analysis</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*QrvNK8fbLl3hwowPWMWnUw.png" /></figure><p>Hierarchical type detection with 80% confidence threshold. Ensures robust type inference even with mixed/dirty data. Currently limited to only few datatypes.</p><h3>6. Zero-Copy Parsing Engine</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*yX9WbH80oC_MrCurXjf90A.png" /></figure><p>Main entry point combining schema inference with data parsing. Single-pass processing from memory-mapped data to Arrow vectors.</p><h3>7. Direct Memory Access (DMA)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7-n-D_xLcnpfYXo5edXDqg.png" /></figure><p>Reads bytes directly from memory-mapped file without buffering. True zero-copy processing — no intermediate data structures.</p><h3>8. Type-Safe Value Conversion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mg1_aIbn7vxB_9I4ZGrT9Q.png" /></figure><p>Converts parsed bytes to strongly-typed Arrow vector values. Maintains type safety while populating columnar Arrow format.</p><h3>9. Entry Point</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*ZRxxeft3qPE5n6S8rwi8MA.png" /></figure><p>Entry point for your application.</p><p>The results ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*Xhs2kgf0PL-PKZ02DAlhQA.png" /></figure><p>Mapping and reading segments average ~1 s for a 200 MB file, whereas <strong>BufferedReader </strong>is 3–5× slower, <strong>Files.readAllLines()</strong> about 7× slower, and alternative readers show even poorer performance.</p><p>Specs — 6 core 12 threads CPU , 16GB RAM , 1 TB SSD</p><h3>Conclusion</h3><p>This wasn’t a breakthrough — not some revolutionary framework or a new algorithm.<br> I’m sure there are people out there who’ve built even smarter, more refined approaches to the same idea.<br> It was simply me exploring what’s possible when we combine <strong>modern Java capabilities</strong> like the <strong>Foreign Function &amp; Memory API</strong> with <strong>next-generation data formats</strong> such as <strong>Apache Arrow</strong>.</p><p>What surprised me was how far Java has come. For years, low-level memory access and native performance were things we looked to C++ or Rust for. But now, with FFM, we can write <em>pure Java</em> that feels just as close to the metal — safe, clean, and incredibly fast.</p><p>The real takeaway isn’t just about performance, it’s about <strong>possibility</strong>.<br> By thinking beyond the heap, we open up a whole new class of high-throughput, low-latency data systems — all within the JVM.</p><p>So, if you’ve ever thought Java was too “managed” for serious memory-level optimization — maybe it’s time to take another look.</p><h3>Motivation</h3><p>This whole experiment started from curiosity rather than a clear goal.<br> I was casually going through the list of new features introduced in recent Java releases — from <strong>JDK 21 onward</strong> — and one feature in particular caught my attention: the <strong>Foreign Function &amp; Memory (FFM) API</strong>.</p><p>At first, it seemed like just another low-level API, but then I realized something:<br> this was Java’s modern, safe, and high-performance <strong>replacement for JNI (Java Native Interface)</strong> — the very tool we’ve relied on for decades to talk to native code.</p><p>And let’s be honest — while <strong>JNI still dominates in some areas</strong>, it’s far from ideal.<br> It’s verbose, risky, and hard to maintain. The idea that Java could finally offer a <em>pure, safe, and high-speed</em> way to work with native memory was genuinely exciting.</p><p>Around the same time, I came across <strong>Vortex</strong>, a new <strong>zero-copy file format</strong> being implemented across multiple languages. That got me thinking:<br> if languages like C++ and Rust are embracing zero-copy, columnar data access — why can’t Java do the same, now that it has FFM?</p><p>That thought became the spark for this small exploration — <br> to see how far we can push Java’s performance when we step outside the heap and start playing directly with native memory.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bdb60ac4252" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring Apache Spark Metrics with Prometheus]]></title>
            <link>https://medium.com/@bhavya.joshi1901/monitoring-apache-spark-metrics-with-prometheus-a2846fe94028?source=rss-7bec68e3439e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2846fe94028</guid>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[grafana-prometheus]]></category>
            <category><![CDATA[spark-driver-memory]]></category>
            <category><![CDATA[apache-spark]]></category>
            <dc:creator><![CDATA[Bhavya Joshi]]></dc:creator>
            <pubDate>Tue, 09 Jul 2024 06:10:22 GMT</pubDate>
            <atom:updated>2024-07-09T06:10:22.942Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*K5RyL39li1e6b33zr_xN-w.png" /></figure><p>Developing a Spark application is a fundamental task; however, optimizing its resource utilization poses a substantial challenge. By meticulously fine-tuning your Spark application, you can significantly mitigate its impact on your system or the cluster resources. In this article, we will examine how you, as a developer, can exploit the full spectrum of functionalities provided by Apache Spark to enhance operational efficiency.</p><p>Please note that this article does not encompass a discussion on Apache Spark’s architecture or the intricacies of resource allocation between the driver and executors. A comprehensive analysis of Apache Spark’s architecture will be presented in a forthcoming article.</p><h3><strong>The Apache Spark UI</strong></h3><p>Apache Spark boasts an impressive user interface (UI) for any Spark job you submit. However, to leverage this visual aid, your application must remain active. Consequently, for testing purposes, I recommend deferring the closure of the Spark session until the very culmination of your Spark application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AjBnX4kKnLAMyK9ALNCFwg.png" /><figcaption><strong>Figure 1 : Apache Spark Environment Details</strong></figcaption></figure><p><strong>Figure 1</strong> shows the resource allocation for spark driver and executor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hvIjv8THltHN0fz_efHPVw.png" /><figcaption><strong>Figure 2: Apache Spark Executor Statistics</strong></figcaption></figure><p><strong>Figure 2</strong> displays the executors tab in the apache spark UI . This tab displays the amount of memory (on-heap and off-heap) allocated to the driver and executors. Other additional metrics may vary based on the version of spark you are using.</p><h4>Setting up Prometheus sink</h4><p>Apache spark is instrumented with Dropwizard metrics library.</p><p>By Default , Apache Spark provides support for Graphite and Prometheus db. In this article , we will be using Prometheus as a sink to capture all the spark metrics.<br>First of all , we need to install Prometheus. You need to download Prometheus and install it directly at your desired location(Local system or Server side).</p><p>Next, we need to configure the “prometheus.yaml” file. Go to the directory where you’ve installed Prometheus. Open the “prometheus.yaml” file and here you need to configure it for your application. For ex- If you are doing a spark-submit locally ,then you need to configure the targets for localhost and similarly for Server-side , you need to put the server URL where you have installed Prometheus in the targets property.<br>Additionally , you will need to use relabeling so that whenever you do a spark-submit , it monitors the running spark application.</p><p>The configuration would look like —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*mDpKoOXZD3jDbFfKHLqO5g.png" /><figcaption><strong>Figure 3 : Prometheus Configuration</strong></figcaption></figure><p>We will be using these source labels for writing queries in Grafana.</p><h4>Setting up Spark metrics configuration</h4><p>Go to Apache Spark’s installed directory and inside the conf folder, there will be a file named “metrics.properties”. We need to enable the Prometheus sink by setting up these properties:</p><blockquote>*.sink.prometheusServlet.class=org.apache.spark.metrics.sink.PrometheusServlet<br>*.sink.prometheusServlet.path=/metrics/prometheus<br>master.sink.prometheusServlet.path=/metrics/master/prometheus<br>applications.sink.prometheusServlet.path=/metrics/applications/prometheus</blockquote><p>In my case, Since I am running the application in client-mode, I have configured the properties in the scala object file only. I have created a map named sparkConfig that includes all the properties required to run apache spark locally as well as configs that enable spark monitoring.</p><blockquote>val sparkConfig = Map(<br> “spark.driver.bindAddress” -&gt; “127.0.0.1”,<br> “spark.driver.host” -&gt; “127.0.0.1”,<br> “spark.executor.memory” -&gt; “4g”,<br> “spark.executor.cores” -&gt; “4”,<br> “spark.sql.default.partition” -&gt; “10”,<br> “spark.metrics.conf.*.sink.prometheusServlet.class” -&gt; “org.apache.spark.metrics.sink.PrometheusServlet”,<br> “spark.metrics.conf.*.sink.prometheusServlet.path” -&gt; “/metrics”,<br> “spark.metrics.conf.*.source.jvm.class” -&gt; “org.apache.spark.metrics.source.JvmSource”<br>)</blockquote><p>Now we’re almost there. You can verify if the metrics are being fetched by Prometheus sink. You will need to launch Prometheus first . If you have installed Prometheus locally then you can access the prometheus endpoint with “localhost:9090”—</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*phwxZGRo0h2VLtg5la-mrA.png" /><figcaption><strong>Figure 4 : Prometheus UI</strong></figcaption></figure><h4>Setting Up DataSource and Creating Grafana Dashboard</h4><p>The final step is creating a grafana dashboard, but before this we need to setup Prometheus Datasource in Grafana.<br>Head up to the datasources tab in the navbar available on the Grafana UI. Click on Add new datasource and then select Prometheus.<br>Provide a name to this datasource and also provide the URL to Prometheus (in case of local setup — <a href="http://localhost:9090/">http://localhost:9090</a> ; in case of Server setup — add your server URL).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wv5vUcf9Nm-3fUSInELQrA.png" /><figcaption><strong>Figure 5 : Prometheus Datasource Configuration</strong></figcaption></figure><p>click on save &amp; test.</p><p>Now, we can proceed to creating a dashboard for monitoring the metrics of our spark application.</p><p>Go to the dashboards tab in the navbar. Click on New dashboard and then proceed to add visualization.</p><p>Under the query input , select the datasource we just created and write a query that fetches the metrics you want with the help of labelling which we provided in the prometheus configuration(ref-Fig 3).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*f3mlghrQoqfRW0boT16oKg.png" /><figcaption><strong>Figure 6 : Sample Query for fetched Driver maxMem</strong></figcaption></figure><p>Similarly, write queries for all the metrics you want in your dashboard and assign proper units to the time-series graph values. Apply and save the dashboard.</p><p>Now, when you will do a spark-submit for your application , it will start fetching these metrics from the prometheus sink to your grafana dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GCCeNYM2bMidcwETy9GFlA.png" /><figcaption><strong>Figure 7 : Spark Executor Metrics</strong></figcaption></figure><h3>Conclusion</h3><p>Establishing a Grafana dashboard allows for effortless monitoring of your Spark application, providing profound insights into the actual memory consumption by both the Spark driver and executors. Additionally, other vital metrics, such as CPU uptime and garbage collection statistics, can be meticulously tracked.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2846fe94028" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>