JVM

jvm3GarbageCollectionDemo

Path
pkg6jvm/jvm3GarbageCollectionDemo.java
Package
pkg6jvm
Study order
3
Run
Single-file source launch
Command
java pkg6jvm/jvm3GarbageCollectionDemo.java

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg6jvm/jvm3GarbageCollectionDemo.java
1package pkg6jvm;2 3/*4 * jvm3GarbageCollectionDemo.java5 * --------------------------6 * Demonstrates reachability, reference types, and GC notifications.7 *8 * KEY IDEAS:9 *   - An object is eligible for GC when no GC root can reach it.10 *   - Reference strength: Strong > Soft > Weak > Phantom.11 *       Strong : never collected while reachable.12 *       Soft   : collected only under memory pressure (good for caches).13 *       Weak   : collected at next GC if only weakly reachable (WeakHashMap).14 *       Phantom: for post-mortem cleanup via a ReferenceQueue (use Cleaner).15 *   - finalize() is deprecated; prefer try-with-resources / java.lang.ref.Cleaner.16 *17 * GC ALGORITHMS (choose with flags; see docs/JVMInternals.md):18 *   -XX:+UseSerialGC | -XX:+UseParallelGC | -XX:+UseG1GC | -XX:+UseZGC | -XX:+UseShenandoahGC19 */20import java.lang.ref.*;21import java.util.*;22 23public class jvm3GarbageCollectionDemo {24 25    public static void main(String[] args) throws InterruptedException {26        // 1) Eligibility: dropping the only reference makes the object collectable27        Object o = new Object();28        System.out.println("strong ref held: " + (o != null));29        o = null;                          // now unreachable -> eligible for GC30        System.out.println("reference cleared -> object now eligible for GC");31 32        // 2) WeakReference: cleared by GC when only weakly reachable33        Object strong = new String("cacheable");34        WeakReference<Object> weak = new WeakReference<>(strong);35        System.out.println("\nweak.get() before clearing strong: " + weak.get());36        strong = null;37        System.gc();38        Thread.sleep(50);                  // give GC a moment39        System.out.println("weak.get() after gc (likely null): " + weak.get());40 41        // 3) WeakHashMap: entries vanish when keys are no longer strongly referenced42        Map<Object, String> cache = new WeakHashMap<>();43        Object key = new Object();44        cache.put(key, "value");45        System.out.println("\nWeakHashMap size with key held: " + cache.size());46        key = null;47        System.gc();48        Thread.sleep(50);49        System.out.println("WeakHashMap size after key cleared: " + cache.size());50 51        // 4) PhantomReference + ReferenceQueue: detect when an object is collected52        ReferenceQueue<Object> queue = new ReferenceQueue<>();53        Object phantomTarget = new Object();54        PhantomReference<Object> phantom = new PhantomReference<>(phantomTarget, queue);55        phantomTarget = null;56        System.gc();57        Thread.sleep(50);58        Reference<?> collected = queue.poll();59        System.out.println("\nPhantom enqueued (object collected): " + (collected == phantom));60 61        System.out.println("\nTip: run with -verbose:gc to see GC events.");62    }63}