JvJava
AdvancedLesson 15 of 16

JVM, Memory & Garbage Collection – Java

How Java code runs, where objects live and typical reference pitfalls.

javac translates source code into bytecode (.class). The JVM loads it, interprets it at first and compiles frequently used spots at runtime into fast machine code with the JIT compiler (HotSpot). That is why Java gets faster after a short warm-up phase.

Memory: the stack holds, per thread, the method calls with local variables and references. The heap holds all objects. The garbage collector (G1, ZGC, …) frees objects that are no longer reachable – you never free anything manually. You can control the heap size at startup:

java -Xms256m -Xmx1g -XX:+UseG1GC MeineApp
java -XX:+UseZGC -Xmx4g MeineApp      # low-latency collector

Even with a GC, memory leaks are possible if references are held unnecessarily – classically: static maps or caches that are never cleaned up. WeakHashMap and WeakReference allow the GC to remove entries.

import java.util.*;

class Cache {
    private static final Map<Integer, byte[]> DATEN = new HashMap<>();   // grows forever!
    static void lade(int id) { DATEN.put(id, new byte[1_000_000]); }
}

Reference comparisons are a source of classic errors: for objects, == compares the address, equals the content. The Integer cache (−128 to 127) and the string pool make the behavior confusing.

Integer a = 127, b = 127;
Integer c = 1000, d = 1000;
System.out.println(a == b);          // true  (from the cache)
System.out.println(c == d);          // false (two objects)
System.out.println(c.equals(d));     // true

String s1 = "hi";
String s2 = new String("hi");
System.out.println(s1 == s2);            // false
System.out.println(s1.equals(s2));       // true
System.out.println(s1 == s2.intern());   // true
WarningBoxing costs memory and time: List<Integer> stores objects instead of int values. In loops with millions of numbers use int[] or IntStream. And an unboxed null (int x = mapWert;) throws a NullPointerException.
TipAnalysis tools in the JDK: jcmd, jstack (thread dump), jmap (heap), jconsole, Java Flight Recorder (-XX:StartFlightRecording). Measure first, then optimize.