Memory and the garbage collector

A Java program does not free its objects. It makes them, it drops the references when it is done, and a collector finds what can no longer be reached and returns the memory. This lesson looks at the two regions that memory lives in, at the numbers the runtime reports, and at five million objects that are made and dropped in a loop.

The heap and the Runtime numbers

The heap is where objects live, and it is shared by every thread. Each thread has a stack of its own for the frames of its calls, and the primitives and references inside those frames. Runtime reports the heap in three numbers: the maximum it may grow to (-Xmx), the total it has taken from the operating system so far, and the part of that which is free.

public class Heap { static long mb(long bytes) { return bytes / (1024 * 1024); } public static void main(String[] args) { Runtime runtime = Runtime.getRuntime(); System.out.println("max heap: " + mb(runtime.maxMemory()) + " MB"); long before = runtime.totalMemory() - runtime.freeMemory(); byte[] block = new byte[32 * 1024 * 1024]; long after = runtime.totalMemory() - runtime.freeMemory(); System.out.println("allocated: " + block.length + " bytes"); System.out.println("used grew by at least 30 MB: " + (after - before >= 30L * 1024 * 1024)); block = null; System.gc(); long collected = runtime.totalMemory() - runtime.freeMemory(); System.out.println("used after gc: " + mb(collected) + " MB"); System.out.println("gc returned"); } }

javac -Xlint:all Heap.java
java Heap

max heap: 2920 MB
allocated: 33554432 bytes
used grew by at least 30 MB: true
used after gc: 1 MB
gc returned

The maximum is a quarter of the memory of this machine, which is the default of a server JVM; -Xmx replaces it. The used bytes are the total minus the free, which is the part of the heap the program has taken. Those numbers change between runs because the collector decides when to work and how much to keep, so the program prints the growth of the allocation as a boolean and not as a figure.

Reachability

The thirty-two megabytes are freed because the variable is set to null, and that is the whole rule: an object the program can still reach is kept, and one it cannot reach is free to be collected. The collector does not count references and does not free an object when its last variable goes out of scope; it runs when it wants and looks for what is reachable from the roots, which are the local variables of every thread, the static fields and the classes.

A reference that is no longer needed and still reachable is the leak of a Java program. A static list that grows, a listener that is never removed, a ThreadLocal that a pool thread keeps: each holds an object that nothing will use again and that no collector may free. The fix is always the same, which is to drop the reference, and the tools that find the holder are the heap dump and its analyser.

System.gc and what it is not

System.gc() asks for a collection; it does not command one. A JVM started with -XX:+DisableExplicitGC ignores the call, and the default collector may start a full collection or not, depending on its own state. A program that calls it in a loop to keep memory low is slower and no safer than one that does not.

The call is useful in one place: a test that measures how much a data structure holds after it is dropped, where a best effort is enough. In a server it is a sign that something holds a reference it should not, and the answer is the reference and not the call.

Five million objects

The second program makes five million records in a loop, adds their fields into a checksum and drops each one when the loop moves on. It is the shape of every program that parses or computes: short-lived objects that the collector takes back:

public class Churn { record Point(int x, int y) { } public static void main(String[] args) { int count = 5_000_000; long start = System.nanoTime(); long checksum = 0; for (int i = 0; i < count; i++) { Point point = new Point(i, i + 1); checksum += point.x() + point.y(); } long ms = (System.nanoTime() - start) / 1_000_000; System.out.println("objects: " + count); System.out.println("checksum: " + checksum); System.out.println("elapsed: " + ms + " ms"); System.out.println("completed: true"); } }

javac -Xlint:all Churn.java
java Churn

objects: 5000000
checksum: 25000000000000
elapsed: 17 ms
completed: true

The checksum is the sum of x and x + 1 for x from 0 to 4,999,999, which is 25,000,000,000,000 and checks that every object was made. The time is short because the objects die young and the collector keeps them in the young generation, which is cheap to empty; the number depends on the machine and the run, as every measurement in this course does.

The same program with -Xmx64m completes as well, which is the point of a generational collector: five million objects do not need five million objects of space, because almost all of them are unreachable by the time the next megabyte is allocated.

What a program can control

Four things, and nothing else. The maximum heap, with -Xmx. The size of the young generation, if the default is wrong for the program. The collector, with -XX:+UseG1GC or one of the others. And how much it holds at once, which is the only one that is a design decision and the only one that fixes a leak of design.

The tools that show what happens are -Xlog:gc for a log of the collections, jcmd for a heap summary and a dump, and jconsole for a graph while the program runs. They are not in the lessons of this course because they need a program that runs for a while; the flag that prints the log is one line and is worth trying on the program above.

Exercises

  1. Run Heap with -Xmx256m and compare the maximum it prints.
  2. Run Churn with -Xlog:gc and count the collections it reports.
  3. Add a static list that keeps every hundredth object of Churn and watch the elapsed time.
  4. Call System.gc() before the allocation of Heap and explain what the used memory shows.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What decides that an object may be collected?

    Answer

    That nothing reachable from the roots refers to it

    The collector walks the references from the roots, and an unreachable object is free.

  2. What does -Xmx set?

    Answer

    The maximum size of the heap

    The flag is the ceiling the heap may grow to, and maxMemory reports it.

  3. What does System.gc() do?

    Answer

    Asks the JVM for a collection, which it may ignore

    The call is a hint, and a JVM may be told to ignore it.

  4. What does this program print? public class Q1 { public static void main(String[] args) { Runtime runtime = Runtime.getRuntime(); System.out.println(runtime.maxMemory() > 0); byte[] block = new byte[1024 * 1024]; System.out.println(block.length); } }

    Answer

    true / 1048576

    A JVM always has a maximum heap, and the array is one mebibyte of bytes.

  5. What is the usual leak of a Java program?

    Answer

    A reference that is kept although nothing will use the object again

    The collector frees only what is unreachable, so a held reference is a leak.

  6. Why is Churn fast although it makes five million objects?

    Answer

    Almost all of them are unreachable immediately, so the young generation is cheap to empty

    The generational collector is built for exactly this shape of allocation.

  7. Which flag prints the collections as they happen?

    Answer

    -Xlog:gc

    The unified logging flag prints a line per collection, and the lessons use it from the shell.

  8. What does this program print? public class Q2 { public static void main(String[] args) { String a = new String("x"); String b = a; a = null; System.out.println(b); System.out.println(a == null); } }

    Answer

    x / true

    b still reaches the object, and a is null after the assignment.

  9. What are the roots the collector starts from?

    Answer

    The local variables of every thread, the static fields and the classes

    Anything reachable from those is kept, and the rest is free.

  10. Why does the program print the growth as a boolean?

    Answer

    The collector decides when to work, so the exact megabytes differ between runs

    Only the fact that the allocation took space is the same on every run.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev