How the garbage collector finds garbage
You call new all day and never free anything, yet a Java program can run for months. The garbage collector does not look for garbage at all: it finds everything still reachable and reclaims the rest, and it is cheapest for objects that die young.
01 The question
In this handler, most orders become useless the moment handle returns. A few are kept in CACHE for good. Nobody writes free(order). How does the JVM tell the two apart?
The answer is not "the object is no longer used". The JVM cannot know what you will use. It uses a stricter, checkable rule: can the program still reach this object?
02 Start from the roots
A root is a reference the program can use directly, without going through another object. Everything reachable by following references from a root is live. Everything else is garbage, because no line of your code can ever get to it again.
- Local variables and parameters in the frames of every running thread, such as
orderabove. - Static fields of loaded classes, such as
CACHE. - A few the JVM holds itself: references held by native code through JNI, objects used as locks right now, and similar.
Note what is not on the list: the object's own fields. An object that refers to others but is not itself reachable keeps nothing alive.
03 Mark what is reachable, sweep the rest
The classic algorithm has two phases. Mark: walk the references from every root and set a mark bit on each object reached. Sweep: go through the heap and free every object without a mark. Here it is on a heap of seven objects.
- root
- not marked
- marked live
- scanning its fields
- just pushed
- freed
A collection starts. Every object's mark bit is clear, and the mark stack is empty. The two roots are a local variable order in a running frame and a static field CACHE.
The sweep drawn here is the textbook version, which leaves free gaps scattered across the heap. HotSpot's current collectors (G1, Parallel, ZGC) instead move the live objects together, by compacting or copying, so free space stays in one piece. The marking is the same idea.
04 Why cycles are no problem
F and G kept references to each other and were still freed. A collector that counts references would have kept them forever.
05 Why young objects are cheap
Look at the cost of marking: it follows live objects only. Dead objects are never visited. That pays off because of a pattern seen in almost every program, the weak generational hypothesis: most objects die very young. Think of the order above, iterators, temporary strings, boxed numbers.
So HotSpot splits the heap in two. New objects go into a young generation, collected often and fast. Objects that survive several young collections (at most 15 by default, -XX:MaxTenuringThreshold) are promoted to the old generation, which is collected far less often. Here is the classic young layout, as in the Serial and Parallel collectors; G1 does the same with the young generation split into regions.
- just allocated or copied
- allocated
- reached: live
- unreached: dead
- copied out
- free
A fresh Eden. Allocation keeps one pointer, top, at the first free byte.
One catch: an old object may point at a young one, and that young object must survive. Scanning the whole old generation each time would undo the savings, so the JVM records old-to-young references as they are written (a card table, with a small write barrier on every reference store) and treats those as extra roots.
06 Watch the collector work
-Xlog:gc (JDK 9 and later) prints one line per collection. This program makes about half a gigabyte of short-lived arrays while keeping only 16 alive at a time:
Read a line as: young collection number 0, heap use went from 23 MB to 1 MB (out of 64 MB), and the program was paused for about a quarter of a millisecond. Almost everything in the young generation was dead, so each pause was tiny. Timings vary by machine; this run was JDK 17 on a laptop, where G1 is the default collector.
If you write byte[] tmp = new byte[100]; and never let tmp leave the loop, you may see no GC lines at all. HotSpot's JIT can prove the array never escapes and skip the heap entirely (escape analysis). Storing it in a field, as above, forces a real allocation.
07 When it bites
A Java memory leak is not memory the JVM lost track of. It is memory you still refer to. The collector will never free an object a root can reach, however useless it is to you.
static Map<Id, Session> SESSIONSCaches that only growA static field is a root, so everything in the map stays live forever. Remove entries, bound the size, or use a cache library with eviction.button.addListener(this)Listeners never removedThe long-lived object keeps a reference to every listener, and each listener keeps everything it refers to.threadLocal.set(bigObject)ThreadLocals in thread poolsPool threads live as long as the pool, and so does their thread-local value. Call remove() when the task ends.System.gc()Asking for a collectionIt is only a request, and it usually triggers a full, slow collection. The JVM already collects when it needs to.protected void finalize()Relying on finalizersThey may run late or never, and they delay freeing. Deprecated since JDK 9. Use try-with-resources to release files and sockets.