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:
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;
}
}
// Enable Serial GC
-XX:+UseSerialGC
// Single-threaded collector
// Good for small applications
// Stop-the-world collection
// Enable Parallel GC
-XX:+UseParallelGC
// Multi-threaded collector
// Good for medium-sized applications
// Stop-the-world collection
// Enable CMS GC
-XX:+UseConcMarkSweepGC
// Concurrent collector
// Good for large applications
// Minimizes application pauses
// Enable G1 GC
-XX:+UseG1GC
// Modern collector
// Good for large heap sizes
// Predictable pause times
// 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
// Enable GC monitoring
-XX:+PrintGCApplicationStoppedTime
-XX:+PrintGCApplicationConcurrentTime
-XX:+PrintGCTimeStamps
// Enable GC cause logging
-XX:+PrintGCCause