JVM

jvm2MemoryAreasDemo

Path
pkg6jvm/jvm2MemoryAreasDemo.java
Package
pkg6jvm
Study order
2
Run
Single-file source launch
Command
java pkg6jvm/jvm2MemoryAreasDemo.java

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

pkg6jvm/jvm2MemoryAreasDemo.java
1package pkg6jvm;2 3/*4 * jvm2MemoryAreasDemo.java5 * --------------------6 * Inspect the JVM runtime memory and demonstrate stack vs heap behavior.7 *8 * RUNTIME DATA AREAS:9 *   - Heap        : objects & arrays (shared, GC-managed). Young + Old generations.10 *   - Stack       : per-thread frames (locals, operand stack). StackOverflowError.11 *   - Metaspace   : class metadata (native memory, replaces PermGen since Java 8).12 *   - PC register : current instruction per thread.13 *   - Native stack: for JNI calls.14 *15 * Try GC behavior with flags, e.g.:16 *   java -Xms64m -Xmx256m -XX:+UseG1GC -verbose:gc jvm2MemoryAreasDemo.java17 */18public class jvm2MemoryAreasDemo {19 20    // Instance fields live inside the object on the HEAP21    static class Box { int value; int[] data = new int[1000]; }22 23    // Each recursive call adds a frame to the STACK24    static int recurse(int depth) {25        return recurse(depth + 1);     // intentionally unbounded to hit the stack limit26    }27 28    public static void main(String[] args) {29        Runtime rt = Runtime.getRuntime();30        long mb = 1024 * 1024;31        System.out.println("=== Heap (Runtime) ===");32        System.out.println("max   : " + rt.maxMemory() / mb + " MB");33        System.out.println("total : " + rt.totalMemory() / mb + " MB");34        System.out.println("free  : " + rt.freeMemory() / mb + " MB");35 36        // Allocate objects on the heap and watch free memory drop37        System.out.println("\nAllocating 10,000 boxes on the heap...");38        Box[] boxes = new Box[10_000];39        for (int i = 0; i < boxes.length; i++) boxes[i] = new Box();40        System.out.println("free after alloc : " + rt.freeMemory() / mb + " MB");41 42        // Release references and suggest GC43        boxes = null;44        System.gc();                                   // a hint, not a guarantee45        System.out.println("free after gc    : " + rt.freeMemory() / mb + " MB (objects became unreachable)");46 47        // Demonstrate the stack limit safely48        System.out.println("\nForcing deep recursion to hit the stack limit...");49        try {50            recurse(0);51        } catch (StackOverflowError e) {52            System.out.println("Caught StackOverflowError -> the call stack is finite (per-thread).");53        }54 55        System.out.println("\nMetaspace holds class metadata; loaded classes ~ " +56                ManagementHint());57    }58 59    // Avoid extra deps: just report number of loaded classes via a simple probe.60    static String ManagementHint() {61        return "(use 'jcmd <pid> VM.metaspace' or -verbose:class to inspect Metaspace)";62    }63}