Java Garbage Collection: How it Works

HOW GARBAGE COLLECTOR WORKS IN JAVA Garbage Collection (GC) in Java is an automatic memory management mechanism provided by the JVM. Its primary role is to free heap memory by removing objects that are no longer used by the application. GC works only on Heap memory; Stack memory is cleared automatically when a method execution ends. The golden rule of Garbage Collection is simple: An object becomes eligible for GC only when it is unreachable. Reachable objects are not collected, while unreachable objects are eligible for collection. Garbage Collection starts from special references known as GC Roots. Instead of scanning the entire heap, the Garbage Collector begins traversal from these roots. GC Roots include local variables in the stack, active threads, static variables, and JNI references. Using reachability analysis, GC determines which objects can be accessed directly or indirectly from GC Roots. Reachable objects are considered alive, while unreachable objects are treated as garbage. Garbage Collection typically works in three phases. In the Mark phase, the Garbage Collector traverses objects starting from GC Roots and marks all reachable objects as alive. No memory is freed during this phase. In the Sweep phase, all unmarked (dead) objects are removed and their memory is freed. A drawback of this phase is memory fragmentation. In the Compact phase, live objects are moved together to eliminate fragmentation, creating continuous free memory and improving allocation performance. The JVM uses Generational Garbage Collection because most objects have a short lifespan. Heap memory is divided into Young Generation (Eden and Survivor spaces) and Old Generation for long-living objects. When an object is created, it is allocated in Eden space. If it survives Minor GC, it moves to Survivor space. After surviving multiple GC cycles, it is promoted to Old Generation. Minor GC occurs when Eden space is full and is fast and frequent. Major or Full GC occurs when Old Generation becomes full and causes Stop-The-World pauses, where all application threads are temporarily paused. Different Garbage Collectors include Serial GC, Parallel GC, CMS (deprecated), and G1 GC. G1 GC is widely used in enterprise applications due to its predictable pause times and better performance on large heaps. #Java #CoreJava #JVM #GarbageCollection #JavaDeveloper #BackendDevelopment #TechLearning #JavaMemory #JVMInternals #SoftwareEngineering #Programming #InterviewPreparation #ComputerScience #Coding

  • text, letter

To view or add a comment, sign in

Explore content categories