How Java Garbage Collection Works: Heap, Generations and Five Collectors, Measured on JDK 25, 27 and 28
Java does not make you free memory. You never write free(), and a program that creates millions of objects does not run out of memory, because a part of the JVM called the garbage collector (GC) finds objects that nothing can reach any more and reuses their space. That works so well that most developers never look at it until something goes wrong: a request that sometimes takes half a second instead of ten milliseconds, a container killed for using too much memory, an OutOfMemoryError in the middle of the night. This article explains it in the order a first-time reader needs it: where objects live, how the collector decides that something is garbage, why the heap is split by age, what the collectors that ship with the JDK do differently, and what happens when the same program runs under each of them. Everything here was run on real JVMs: JDK 25 (the current long-term-support release), JDK 27, and an early-access build of JDK 28. It is a rewrite of the article that used to live at this address, and the last section lists what the old version got wrong. What was run, and what was not. Every number and every console block below comes from a file in the companion module (asmhatre/javademos, module gc-basics), regenerated by one script. Versions: Temurin 25.0.5.1 (LTS), Temurin 27.0.1.1 (GA 15 September 2026), and Temurin 28+25, an early-access build of JDK 28 (GA is scheduled for March 2027, so anything seen only there can still change). Timings came from a 2 vCPU sandbox, so read them as shape, not as results. Container behaviour was tested with real docker run --cpus --memory limits. What was not run: multi-terabyte heaps, a real Spring application, and Windows or macOS. Statements about JEPs and release plans come from the OpenJDK and InfoQ pages linked at the end and are marked as documentation, not as observations.