Command Palette

Search for a command to run...

Back to the lesson: Topic 14.3 — Garbage Collection
Core Java · Example 1 of 3 Java 9+

Mark and sweep by hand

A model of what a tracing collector does. The nodeA/nodeB cycle is collected because tracing starts from roots; reference counting would never free it.

The garbage collector frees objects that can no longer be reached from any GC root, so you never free memory by hand. Modern JVMs split the heap into generations because most objects die young, and offer collectors with different goals: G1 (the default since Java 9) balances throughput and pauses, ZGC and Shenandoah keep pauses around a millisecond, Parallel maximises throughput.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Extend the mark-and-sweep model so oldCart becomes reachable again by adding it as a second root, and print the new garbage list.

02

Write an LRU cache of capacity 3 with LinkedHashMap, insert keys 1 to 5, read key 3 and insert key 6; print the keys.

03

Show the difference between a GC root reference and a local that is out of scope: write a method that builds a big list and returns only its size, and explain in a comment why the list is collectable after the method returns.

Explain it without notes

01

How does the JVM decide that an object is garbage? What are GC roots?

02

Explain the generational hypothesis and how a minor GC works.

03

Compare G1, ZGC and Parallel GC. When would you pick each?

04

What is a memory leak in Java, and how would you find one?

Mark and sweep by hand Java 9+
Sign in to run this example in your browser.

Expected output

roots:   [order]
live:    [order, items, customer, address]
garbage: [oldCart, oldItem, nodeA, nodeB]
heap now holds 4 objects