← Back to Module 4

Garbage Collection

Garbage Collection Basics

What is Garbage Collection?

Garbage Collection (GC) is the process of automatically managing memory by identifying and removing objects that are no longer needed by the program. The garbage collector:

Object Reachability

public class ReachabilityExample {
    public static void main(String[] args) {
        // Strong reference
        String str = new String("Hello");
        
        // Weak reference
        WeakReference weakRef = new WeakReference<>(str);
        
        // Soft reference
        SoftReference softRef = new SoftReference<>(str);
        
        // Phantom reference
        PhantomReference phantomRef = new PhantomReference<>(str, new ReferenceQueue<>());
        
        // Make object unreachable
        str = null;
    }
}

Garbage Collection Algorithms

Mark and Sweep

Copying

Mark and Compact

Garbage Collectors in Java

Serial GC

// Enable Serial GC
-XX:+UseSerialGC

// Single-threaded collector
// Good for small applications
// Stop-the-world collection

Parallel GC

// Enable Parallel GC
-XX:+UseParallelGC

// Multi-threaded collector
// Good for medium-sized applications
// Stop-the-world collection

CMS (Concurrent Mark Sweep)

// Enable CMS GC
-XX:+UseConcMarkSweepGC

// Concurrent collector
// Good for large applications
// Minimizes application pauses

G1 (Garbage First)

// Enable G1 GC
-XX:+UseG1GC

// Modern collector
// Good for large heap sizes
// Predictable pause times

GC Tuning

GC Parameters

// Heap size settings
-Xms2g -Xmx4g

// GC pause time target
-XX:MaxGCPauseMillis=200

// GC logging
-verbose:gc
-XX:+PrintGCDetails
-XX:+PrintGCDateStamps
-Xloggc:gc.log

// GC statistics
-XX:+PrintGCStatistics

GC Monitoring

// Enable GC monitoring
-XX:+PrintGCApplicationStoppedTime
-XX:+PrintGCApplicationConcurrentTime
-XX:+PrintGCTimeStamps

// Enable GC cause logging
-XX:+PrintGCCause

GC Best Practices

Memory Management

GC Optimization

Common Issues

Video Content