Java.Core.How does garbage collection work in Java?

🧹 What is Garbage Collection (GC)?

In Java, garbage collection is the process of automatically reclaiming memory by identifying and removing objects that are no longer reachable from your program. This means objects that your code can no longer access or use will eventually be cleaned up by the JVM’s Garbage Collector.


⚙️ How does it work?

1. Reachability Analysis

  • The JVM keeps track of “live” objects—these are objects that are still reachable (referenced) by the application.
  • Any object that cannot be reached through a chain of references from root objects (like static variables, active threads, local variables in methods) is considered garbage.

2. Phases of GC Process

Java GC usually works in phases:

PhaseDescription
MarkIdentify all reachable objects by traversing from root objects.
SweepRemove all unreachable objects, freeing up memory.
Compact (optional)Rearrange remaining objects to avoid fragmentation.

3. Generational Garbage Collection

To optimize performance, Java divides memory into generations:

GenerationPurpose
Young GenerationNew objects are created here. Short-lived objects are collected quickly.
Old Generation (Tenured)Long-lived objects are promoted here. Collected less frequently.
Permanent Generation (Metaspace)Class metadata, method data, and interned strings live here (in older JVM versions). In modern Java (Java 8+), this is replaced by Metaspace, which is outside the heap.

4. GC Algorithms

Java has several GC algorithms, each suited for different scenarios:

GC AlgorithmDescription
Serial GCSimple, stops the world, works well for single-threaded apps.
Parallel GCMultiple threads for GC, suited for throughput-focused apps.
CMS (Concurrent Mark Sweep)Low-latency GC, works alongside application threads (deprecated).
G1 (Garbage First)Balances throughput and low-latency, splits heap into regions.
ZGC / ShenandoahVery low-latency GC, handles very large heaps (newer).

5. Triggers for GC

Garbage collection can be triggered by:

  • Memory pressure (low available heap space).
  • Explicit requests (like System.gc() — though this is just a suggestion to the JVM, not a command).

Example

public class GarbageCollectionDemo {
    public static void main(String[] args) {
        String temp = new String("Hello");
        temp = null; // Now the "Hello" String object is eligible for GC
        System.gc(); // This is only a hint to JVM, not guaranteed
    }
}

📊 Key Points to Remember

✅ GC is automatic — no need to manually free memory.
✅ You can tune GC behavior using JVM options, like -XX:+UseG1GC, -Xms, -Xmx, etc.
✅ Modern GC (like G1 or ZGC) is highly optimized for large applications and low-pause performance.

This entry was posted in Без рубрики. Bookmark the permalink.