<?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 Raphael Wijesekera on Medium]]></title>
        <description><![CDATA[Stories by Raphael Wijesekera on Medium]]></description>
        <link>https://medium.com/@shyanraphael?source=rss-5452471ff20c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Raphael Wijesekera on Medium</title>
            <link>https://medium.com/@shyanraphael?source=rss-5452471ff20c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 11:19:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shyanraphael/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[If HTTP Is Synchronous, How Do Microservices Achieve Asynchronous Behavior?]]></title>
            <link>https://medium.com/@shyanraphael/if-http-is-synchronous-how-do-microservices-achieve-asynchronous-behavior-bc7124b4858b?source=rss-5452471ff20c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc7124b4858b</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[monolithic-architecture]]></category>
            <category><![CDATA[synchronous]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[http-communication]]></category>
            <dc:creator><![CDATA[Raphael Wijesekera]]></dc:creator>
            <pubDate>Tue, 07 Jul 2026 03:32:01 GMT</pubDate>
            <atom:updated>2026-07-07T03:32:01.515Z</atom:updated>
            <content:encoded><![CDATA[<h3>What are Synchronous and Asynchronous?</h3><p>· <strong>Synchronous Communication:</strong> Services communicate directly using protocols like HTTP/REST or gRPC, where the sender waits for an immediate response from the receiver.</p><p>· <strong>Asynchronous Communication:</strong> Services exchange messages through message brokers such as Kafka or RabbitMQ, allowing them to operate independently without waiting for responses.</p><h4>Simple Definition for Synchronous &amp; Asynchronous</h4><p>· <strong>Synchronous</strong> communication is like a phone call. You ask a question and stay on the line, doing nothing else, until the other person answers. You can’t hang up and continue your day until you get a reply.</p><p>· <strong>Asynchronous</strong> communication is like sending a text message or an email. You send it and go about your business. The other person replies whenever they get to it, and you pick the conversation back up at that point.</p><h3>Fundamentals of Microservices Communication</h3><p>The fundamentals of microservices communication in a system design involves understanding how these independent services interact to form an interconnected application. Below are the key aspects:</p><p>· <strong>Synchronous Communication:</strong> Services communicate in real time using protocols like REST or gRPC, where the sender waits for a response before continuing.</p><p>· <strong>Asynchronous Communication:</strong> Services exchange messages through brokers like Kafka, RabbitMQ, or AWS SQS without waiting for an immediate response.</p><p>· <strong>Message Brokers:</strong> Enable decoupled communication by handling message delivery between services. Examples include Kafka, RabbitMQ, and AWS SNS/SQS.</p><p>· <strong>Service Discovery:</strong> Helps services locate and communicate with each other in dynamic environments. Common tools are Consul and Eureka.</p><p>· <strong>Load Balancing:</strong> Distributes requests across multiple service instances to improve performance and availability. Tools include NGINX and HAProxy.</p><p>· <strong>Circuit Breakers:</strong> Prevent cascading failures by stopping requests for unhealthy services until they recover.</p><p>· <strong>API Gateway:</strong> Provides a single-entry point for clients and manages routing, authentication, rate limiting, and logging.</p><h3>What are common communication protocols used in Microservices?</h3><p>Microservices architecture relies on various communication protocols to enable efficient and effective interaction between services. Here are some of the commonly used communication protocols in microservices:</p><h4>1. HTTP/ HTTPS</h4><p><strong>a. REST (Representational State Transfer): </strong>Uses standard HTTP methods such as GET, POST, PUT and DELETE for synchronous communication and CRUD (Create, Read, Update, Delete) operations.</p><p><strong>b. GraphQL:</strong> Allows clients to request only the required data, where it reduces over-fetching and under-fetching.</p><p><strong>c. gRPC (Remote Procedure Calls): </strong>High-performance RPC framework that uses HTTP/2 and Protocol Buffers for last, low-latency communication.</p><p><strong>d. WebSockets:</strong> Provides full-duplex communication over a single connection, ideal for real-time communication and applications.</p><h4>2. Message Queues</h4><p><strong>a. AMQP (Advanced Message Queuing Protocol): </strong>Used by brokers like RabbitMQ for reliable asynchronous messaging between services.</p><p><strong>b. Kafka:</strong> A distributed streaming platform designed for high-throughput and fault-tolerant messaging.</p><p><strong>c. MQTT (Message Queuing Telemetry Transport):</strong> A lightweight messaging protocol commonly used in IoT and low-bandwidth environments.</p><h4>3. Other Communication Technologies</h4><p><strong>a. ZeroMQ:</strong> High-performance messaging library supporting patterns such as publish-subscribe and request-reply.</p><p><strong>b. SOAP (Simple Object Access Protocol):</strong> XML-based protocol used in some enterprise applications due to strict standards and security features.</p><h3>Synchronous Communication Patterns</h3><p>Synchronous communication in microservices occurs when a single service sends a request and waits for a response before continuing. It is commonly used for real-time operations that need immediate results.</p><ul><li><strong>Client-Side Load Balancing:</strong> The client maintains a list of available service instances and selects one using a load-balancing algorithm. Used for distributing traffic among multiple service instances to ensure high availability and reliability.</li><li><strong>Server-Side Load Balancing:</strong> A load balancer sits between the client and service instances, routing requests based on a load-balancing strategy. Provides centralized load management and simplifies scaling.</li><li><strong>API Gateway:</strong> Acts as a single-entry point for all client requests and routes them to appropriate microservices. Also handles authentication, rate limiting, logging, and monitoring.</li><li><strong>Service Registry and Discovery:</strong> Services register themselves with a registry, and clients query it to discover available instances. Useful in dynamic environments where services frequently scale up or down.</li><li><strong>Service Mesh:</strong> A dedicated infrastructure layer that manages service-to-service communication, including load balancing, service discovery, security, and observability. Commonly used in large microservices deployments.</li><li><strong>Circuit Breaker:</strong> Detects service failures and temporarily stops requests for failing services until they recover. Helps prevent cascading failures and improve fault tolerance.</li><li><strong>Bulkhead:</strong> Isolates different parts of the system by allocating separate resources and limits to each component. Prevents failures in one component from affecting others.</li></ul><h3>Asynchronous Communication Patterns</h3><p>Asynchronous communication in microservices allows services to interact without waiting for an immediate response. This approach helps decouple services, improve scalability and increase system flexibility.</p><ul><li><strong>Publish-Subscribe (Pub-Sub):</strong> Messages are published to a topic or channel, and multiple subscribers can receive them. Commonly used for event-driven architecture, real-time notifications, and broadcasting events to multiple services.</li><li><strong>Event Sourcing:</strong> Instead of storing the current state, the system stores a sequence of events representing state changes. The current state is reconstructed by replaying these events. Useful for auditability and consistency in distributed systems.</li><li><strong>Command Query Responsibility Segregation (CQRS):</strong> Separates read and write operations into different models, often combined with Event Sourcing. Improves performance, scalability, and maintainability by optimizing reading and write paths independently.</li><li><strong>Saga Pattern:</strong> Manages distributed transactions by breaking them into smaller steps, where each step has a compensating action for rollback if a failure occurs. Ensures data consistency across multiple services without using distributed transactions.</li><li><strong>Dead Letter Queue (DLQ):</strong> A special queue that stores messages that cannot be processed successfully. Helps handle failures and ensures that messages are not lost.</li><li><strong>Backpressure:</strong> Controls the flow of messages when producers generate data faster than consumers can process it. Prevents system overload and maintains stability under heavy load.</li><li><strong>Polling:</strong> Services periodically check a shared resource, such as a database or message queue, for new messages or tasks. Suitable for simple integrations and batch-processing scenarios.</li></ul><h3>Monolith vs Microservices</h3><figure><img alt="Diagram comparing a monolithic node.js API service with users, threads, and posts grouped together, to a microservices architecture with separate services for users, threads, and posts." src="https://cdn-images-1.medium.com/max/1024/1*4pS8KP56zhKq__BBZh0QLQ.png" /><figcaption>Monolith vs microservices: One service vs three</figcaption></figure><h4>Monolithic Architecture</h4><p>· All processes are tightly coupled and run as a single service. So, if one process of the application experiences a spike in demand, the entire architecture must be scaled.</p><p>· Adding or improving a monolithic application’s features becomes more complex as the code base grows. This complexity limits experimentation and makes it difficult to implement new ideas.</p><p>· Monolithic architecture adds risk for application’s availability because many dependent and tightly coupled processes increase the impact of a single process failure.</p><h4>Microservices Architecture</h4><p>· An application built as independent components that run each application process as a service. These services communicate via a well-defined interface using lightweight APIs (Application Program Interface).</p><p>· Services are built for business capabilities, and each service performs a single function. As they are independently run, each service can be updated, deployed and scaled to meet demand for a specific function of an application.</p><h3>Characteristics of Microservices</h3><p>1. <strong>Autonomous</strong>: Each component service in a microservices architecture can be developed, deployed, operated, and scaled without affecting the functioning of other services. Services do not need to share any of their code or implementation with other services. Any communication between individual components happens via well-defined APIs.</p><p>2. <strong>Specialized: </strong>Each service is designed for a set of capabilities and focuses on solving a specific problem. If developers contribute more code to a service over time and the service becomes complex, it can be broken into smaller services.</p><h3>Benefits of Microservices</h3><p>Before getting deeper into communication patterns, it’s worth pausing on why teams take on the added complexity of a distributed system in the first place. The payoff shows up less in raw performance and more in how an organization is able to build and operate software over time.</p><ol><li><strong>Agility:</strong> Splitting an application into small services naturally splits the organization into small, independent teams that each own their slice of the system. Because each team works within a smaller, well-understood context, they can move faster and make decisions without waiting on everyone else and that speed compounds across the whole organization rather than being capped by one team’s pace.</li><li><strong>Flexible scaling: </strong>A monolith has to be scaled as a whole even if only one feature is under load. Microservices let each service scale independently to match the demand on the specific feature it powers, which means infrastructure can be right-sized, the cost of running a given feature can be measured accurately, and the system stays available even when one part of it spikes.</li><li><strong>Easy deployment:</strong> Because each service is a small, independently deployable unit, microservices fit naturally with continuous integration and continuous delivery. Teams can ship a new idea, watch how it performs, and roll it back cheaply if it doesn’t work and that low cost of failure is what makes frequent experimentation and faster time-to-market realistic.</li><li><strong>Technological freedom:</strong> There’s no requirement that every service use the same language, framework, or database. Each team can pick the tool best suited to the problem their service solves, rather than being locked into one stack for the entire application.</li><li><strong>Reusable code: </strong>Small, well-defined services act like building blocks. A service built to solve one problem can often be reused as a component in a completely different feature, so new capabilities can be assembled from existing services instead of being built from scratch every time.</li><li><strong>Resilience:</strong> In a monolith, one failing component can bring the entire application down with it. In a microservices architecture, services are independent enough that a single failure tends to degrade one feature rather than crash the whole system yet the application keeps running in a reduced state instead of going offline entirely.</li></ol><h3>References</h3><ul><li><a href="https://www.geeksforgeeks.org/software-engineering/monolithic-vs-microservices-architecture/">Monolithic vs. Microservices Architecture</a> (GeeksforGeeks)</li><li><a href="https://www.geeksforgeeks.org/system-design/microservices/">Microservices</a> (GeeksforGeeks)</li><li><a href="https://www.geeksforgeeks.org/system-design/microservices-communication-patterns/">Microservices Communication Patterns</a> (GeeksforGeeks)</li><li><a href="https://aws.amazon.com/microservices/">Microservices</a> (AWS)</li><li><a href="https://medium.com/@mmz.zaeimi/synchronous-vs-asynchronous-communication-in-microservices-integration-f4dd36478fd2">Synchronous vs. Asynchronous Communication in Microservices Integration</a> (Medium)</li><li><a href="https://www.techtarget.com/searchapparchitecture/tip/Synchronous-vs-asynchronous-communication-The-differences">Synchronous vs asynchronous communications: A complete guide</a> (TechTarget)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc7124b4858b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Java: Architecture, JVM Internals, Memory, and Garbage Collection]]></title>
            <link>https://medium.com/@shyanraphael/understanding-java-architecture-jvm-internals-memory-and-garbage-collection-b4cf081ece96?source=rss-5452471ff20c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4cf081ece96</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[garbage-collection]]></category>
            <category><![CDATA[java-architecture]]></category>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[java-memory-model]]></category>
            <dc:creator><![CDATA[Raphael Wijesekera]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 06:48:40 GMT</pubDate>
            <atom:updated>2026-06-30T10:59:48.004Z</atom:updated>
            <content:encoded><![CDATA[<p>Java has stayed near the top of the programming world for almost three decades for one main reason: it was built around a simple but powerful idea: <strong>write once, run anywhere</strong>. That idea is only possible because of a carefully layered architecture sitting underneath every .java file you write. This article walks through that architecture, explains the difference between the JDK and the JVM, shows how classes and methods actually get loaded and executed, where your variables and constants physically live in memory, and how the garbage collector quietly cleans up after you.</p><h3>1. The Architecture of Java</h3><p>When you compile and run a Java program, several distinct components cooperate behind the scenes:</p><pre>.java file  →  javac (compiler)  →  .class file (bytecode)  →  JVM  →  Machine code</pre><ol><li><strong>Source code (.java): </strong>the human-readable code you write.</li><li><strong>Compiler (javac): </strong>converts source code into <strong>bytecode</strong>, a platform-independent instruction set stored in .class files.</li><li><strong>Bytecode (.class): </strong>not machine code, and not source code either. It’s an intermediate format that any JVM, on any operating system, can understand.</li><li><strong>JVM (Java Virtual Machine): </strong>reads the bytecode and either interprets it or compiles it just-in-time into native machine instructions for the actual CPU.</li></ol><p>This separation is what gives Java its portability: the compiler doesn’t need to know anything about the target machine, and the JVM doesn’t need to know anything about your source language. As long as a platform has a JVM implementation, your compiled bytecode will run on it unchanged.</p><p>Three acronyms describe the layers involved, and they’re often confused with one another:</p><ul><li><strong>JDK</strong> (Java Development Kit): everything needed to <em>develop</em> Java applications.</li><li><strong>JRE</strong> (Java Runtime Environment): everything needed to <em>run</em> Java applications.</li><li><strong>JVM</strong> (Java Virtual Machine): the engine that actually <em>executes</em> bytecode.</li></ul><p>They nest inside one another like Russian dolls: <strong>JDK ⊃ JRE ⊃ JVM</strong>.</p><h3>2. JDK vs JVM</h3><h3>JDK (Java Development Kit)</h3><p>The JDK is the full toolbox for a Java developer. It includes:</p><ul><li>The <strong>JRE</strong> (so it can also run programs)</li><li>javac — the compiler that turns .java files into .class bytecode</li><li>javadoc — generates documentation from code comments</li><li>jar — packages compiled classes into distributable archives</li><li>jdb — the debugger</li><li>Other utilities (jps, jstack, jconsole, etc.) for inspecting running JVMs</li></ul><p>You need the JDK only if you intend to <strong>write and compile</strong> Java code.</p><h3>JRE (Java Runtime Environment)</h3><p>The JRE is what’s needed to <strong>run</strong> an already-compiled Java program. It bundles:</p><ul><li>The <strong>JVM</strong></li><li>Core class libraries (java.lang, java.util, java.io, etc.)</li><li>Supporting configuration files</li></ul><p>It has no compiler yet it can execute bytecode, but it can’t produce it. (Note: since Java 11, Oracle stopped shipping the JRE as a separate standalone download; modern JDK distributions include everything, but the conceptual layering still holds.)</p><h3>JVM (Java Virtual Machine)</h3><p>The JVM is an abstract specification where a contract that says “here is how Java bytecode must behave.” Multiple implementations exist (HotSpot from Oracle/OpenJDK, OpenJ9 from Eclipse, GraalVM, Azul’s Zing, etc.), but they all honor the same specification so that bytecode behaves identically regardless of which one runs it.</p><p>Internally, every JVM implementation is built from four subsystems:</p><p>Subsystem Responsibility <strong>Class Loader Subsystem</strong> Loads, links, and initializes .class files <strong>Runtime Data Areas</strong> Memory regions: heap, stacks, method area, PC registers <strong>Execution Engine</strong> Interpreter, JIT compiler, and garbage collector <strong>Native Method Interface (JNI)</strong> Bridge to native (C/C++) libraries</p><p>The next two sections dig into the first and the third of these.</p><h3>3. How the JVM Loads Classes and Methods</h3><p>Before a single line of your code runs, the JVM has to find your compiled classes, verify them, and prepare them for execution. This is the <strong>Class Loader Subsystem</strong>’s job, and it happens in three well-defined phases: <strong>Loading → Linking → Initialization</strong>.</p><h3>Step 1: Loading</h3><p>Three built-in class loaders work in a hierarchy, each delegating upward before trying to load anything itself:</p><p><strong>1.Bootstrap ClassLoader</strong></p><ul><li>Written in native code, loads the core Java classes (java.lang.*, java.util.*) from the JDK’s core modules.</li><li>This is the root class loader, which is built into the JVM.</li></ul><p><strong>2.Platform/Extension ClassLoader</strong></p><ul><li>This class loader Loads classes from platform-specific extension libraries, often from the lib/ext directory or Java modules.</li><li>Parent of the class loader is the Bootstrap ClassLoader.</li></ul><p><strong>3.Application/System ClassLoader</strong></p><ul><li>Loads classes from your application’s classpath (your own .class files and third-party JARs).</li><li>The parent of this class loader is the Platform ClassLoader.</li></ul><p><strong>4.Custom ClassLoaders</strong></p><ul><li>Own class loaders can be written by developers by extending ClassLoader.</li><li>This gives the opportunity for advanced use cases such as dynamic loading, class reloading, sandboxing or even encrypting files.</li></ul><p>Each loader is delegated to its parent before attempting to load a class on its own, which helps maintain security and also avoid loading duplicated definitions.</p><figure><img alt="Class Loader Subsystem" src="https://cdn-images-1.medium.com/max/1024/1*5SAsqD9GGDEVGRPsNDvt8A.png" /><figcaption>Subsystems of the ClassLoader</figcaption></figure><p>This works through the <strong>delegation model</strong>: when a class needs to be loaded, the request is passed up to the parent loader first. Only if the parent can’t find the class does the child attempt to load it itself. This prevents core classes like java.lang.String from ever being accidentally overridden by application code.</p><h3>Step 2: Linking</h3><p>Linking itself has three sub-phases:</p><ol><li><strong>Verification: </strong>the bytecode verifier checks that the .class file is structurally valid and doesn&#39;t violate JVM safety rules (no stack overflows from bad bytecode, no illegal type casts, no accessing private data it shouldn&#39;t, etc.). This is a key part of Java&#39;s security model.</li><li><strong>Preparation: </strong>memory is allocated for the class’s static (class-level) variables, and they&#39;re set to default values (0, false, null), not their actual initial values yet.</li><li><strong>Resolutio: </strong>symbolic references in the bytecode (like the name of a class or method being called) are replaced with direct references into the runtime memory structures.</li></ol><h3>Step 3: Initialization</h3><p>Static initializer blocks and static variable assignments are executed, in the order they appear in the source code, starting from the topmost parent class down to the class itself. This is the point where static int x = compute(); actually runs compute().</p><h3>How methods come into play</h3><p>Once a class is loaded, its method bytecode lives in the <strong>Method Area</strong> (see the next section). When a method is invoked:</p><ol><li>The <strong>Execution Engine</strong> first <strong>interprets</strong> the bytecode line-by-line, this is slower but starts instantly.</li><li>The JVM tracks how often each method is called. Frequently executed (“hot”) methods are handed to the <strong>JIT (Just-In-Time) compiler</strong>, which compiles them directly into native machine code so subsequent calls run at near-native speed.</li><li>HotSpot, for example, uses two JIT compilers: <strong>C1</strong> (client compiler, optimizes quickly for fast startup) and <strong>C2</strong> (server compiler, applies aggressive optimizations for long-running hot code) and can escalate a method from interpreted, to C1-compiled, to C2-compiled as it gets hotter.</li></ol><p>This mixed interpret-then-compile strategy is why Java programs often feel slightly slower at startup but speed up the longer they run.</p><h3>4. Where Variables and Constants Are Stored in Memory</h3><p>The JVM divides memory into several distinct <strong>runtime data areas</strong>, each with different lifetimes, scopes, and thread-sharing rules.</p><p>Memory Area Shared Across Threads? What Lives There <strong>Heap</strong> Yes Objects, instance variables, arrays <strong>Method Area / Metaspace</strong> Yes Class metadata, static variables, runtime constant pool, method bytecode <strong>Stack</strong> No (one per thread) Local variables, method parameters, partial results, stack frames <strong>PC Register</strong> No (one per thread) Address of the currently executing instruction <strong>Native Method Stack</strong> No (one per thread) State for native (non-Java) method calls</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mx9zm3CRfE6uD5Z_MwRPhQ.png" /><figcaption>Memory Layout of JVM</figcaption></figure><h3>Heap</h3><p>This is where every object you create with new ends up along with its instance (non-static) fields. It&#39;s shared by all threads and is the primary area the garbage collector manages. It&#39;s further subdivided internally for GC purposes (see section 5).</p><h3>Method Area (called Meta space since Java 8, replacing the old “PermGen”)</h3><p>This holds per-class data: the structure of each class, static variables, and the <strong>runtime constant pool</strong> which is a per-class table of literals and symbolic references (like method names and class references) resolved during linking. Method bytecode itself is also stored here.</p><h3>Stack (where local variables actually live)</h3><p>Every thread gets its own stack, made up of <strong>stack frames </strong>where one frame is pushed for each method call and popped when that method returns. A frame holds:</p><ul><li>The method’s <strong>local variables</strong> (including parameters)</li><li>An operand stack for intermediate computation</li><li>A reference back to the runtime constant pool</li></ul><p>This is the key detail people often get wrong: a local variable that holds a primitive (int, double, boolean, etc.) stores the actual value directly on the stack. A local variable that holds an object <strong>reference</strong> stores just the reference (a pointer) on the stack the actual object it points to lives on the heap.</p><pre>void example() {<br>    int x = 10;              // x lives directly on the stack<br>    String s = new String(&quot;hi&quot;); // s (the reference) is on the stack,<br>                                   // the String object itself is on the heap<br>}</pre><h3>Constants (final variables and the String pool)</h3><ul><li><strong>Compile-time constants</strong>: a final variable of a primitive type or String, initialized with a constant expression (e.g., final int MAX = 100;), is resolved by the compiler and <strong>inline directly into the bytecode</strong> wherever it&#39;s used — it doesn&#39;t even need a runtime lookup.</li><li><strong>String literals</strong> (&quot;hello&quot;) are stored in the <strong>String Constant Pool</strong>, a special deduplicated cache (located inside the heap since Java 7) that ensures identical literal strings share the same memory rather than creating duplicate objects.</li><li><strong>Class-level (</strong><strong>static) constants</strong> that aren&#39;t simple compile-time literals are stored as static fields in the <strong>Method Area</strong>, referenced through the runtime constant pool.</li></ul><h3>5. How the Garbage Collector Works</h3><p>Java doesn’t require you to manually free memory, therefore the <strong>Garbage Collector (GC)</strong> automatically reclaims heap memory occupied by objects no longer reachable by your program. Here’s how it actually pulls that off.</p><h3>The core idea: reachability, not reference counting</h3><p>The GC doesn’t ask “has this object’s reference count hit zero?” Instead, it starts from a known set of <strong>GC Roots</strong> which are local variables on active thread stacks, static fields, active JNI references and traces every object reachable from those roots. Anything <em>not</em> reached during that trace is, by definition, garbage.</p><h3>Generational hypothesis</h3><p>Most JVM garbage collectors rely on an empirical observation: <strong>most objects die young</strong>. Short-lived objects (loop variables, temporary calculations) vastly outnumber long-lived ones (caches, singletons). So the heap is split into generations:</p><ol><li><strong>Young Generation</strong> — further divided into:</li></ol><ul><li><strong>Eden space</strong> — where new objects are first allocated</li><li><strong>Survivor spaces (S0, S1)</strong> — where objects that survive a GC cycle are moved</li></ul><p><strong>2. Old Generation (Tenured)</strong> — long-lived objects that have survived many young-gen collections get <strong>promoted</strong> here.</p><h3>Minor GC vs Major/Full GC</h3><ul><li><strong>Minor GC</strong> — cleans the Young Generation only. It’s frequent but fast, since most objects in Eden are already dead by the time it runs.</li><li><strong>Major/Full GC</strong> — cleans the Old Generation (often along with the rest of the heap). It’s much rarer but considerably more expensive, since it scans a larger, longer-lived set of objects.</li></ul><h3>The actual algorithm: Mark, Sweep, Compact</h3><ol><li><strong>Mark: </strong>starting from GC Roots, the collector traces and marks every reachable object.</li><li><strong>Sweep: </strong>unmarked (unreachable) objects are identified as garbage and their memory is reclaimed.</li><li><strong>Compact: </strong>surviving objects are moved together to eliminate fragmentation, leaving one contiguous free block for fast future allocation.</li></ol><p>Young-generation collections typically use a variant called a <strong>copying collector</strong>: live objects in Eden and one survivor space are copied into the other survivor space (or promoted to Old Gen), and the source space is then wiped entirely, which is extremely fast since there’s no need to individually track dead objects.</p><h3>Stop-the-World pauses</h3><p>Most GC algorithms must briefly pause all application threads (a “<strong>stop-the-world</strong>” pause) to safely trace and move objects without the program mutating references mid-scan. Much of the evolution of GC algorithms has been about shrinking these pauses:</p><p>Collector Characteristics <strong>Serial GC</strong> Single-threaded, simplest, suited to small heaps/single-core machines <strong>Parallel GC</strong> Multi-threaded version of Serial GC, optimized for throughput <strong>G1 GC</strong> (default in modern JDKs) Divides the heap into many small regions, collects the most garbage-dense ones first, balances throughput and pause time <strong>ZGC</strong> Designed for very large heaps with sub-millisecond pause times, does most work concurrently <strong>Shenandoah</strong> Similar low-pause goals to ZGC, developed by Red Hat</p><h3>Object aging and promotion</h3><p>Each object carries an internal <strong>age counter</strong>, incremented every time it survives a minor GC in the survivor space. Once it crosses a configurable age threshold, it’s promoted to the Old Generation where the JVM’s bet that an object which has survived this long is probably going to stick around for a while, so it’s not worth re-checking it on every fast young-gen cycle.</p><h3>Summary</h3><p>A single line of Java code touches every layer described above: it’s compiled into bytecode by the JDK’s javac, loaded and verified by the JVM&#39;s class loaders, executed by an interpreter that may hand it off to a JIT compiler, with its local variables sitting on a thread&#39;s stack, its objects living on the heap, and a generational garbage collector quietly working in the background to reclaim memory the moment it&#39;s no longer reachable. Understanding this pipeline from source file to running machine instructions is what separates &quot;I can write Java&quot; from &quot;I understand why Java behaves the way it does.&quot;</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4cf081ece96" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>