Garbage collection · Topic 2 of 6
The heap and generations
Definition​
Objects live on the heap. Most objects die young, so the collector splits the heap into a young area, where new objects start and are cleaned often and cheaply, and an old area for objects that survive. Cleaning the young area is called a minor collection.
Example code​
Creating garbage and watching the collector run
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
class Demo {
public static void main(String[] args) {
long before = totalCollections();
for (int i = 0; i < 3_000_000; i++) {
byte[] temporary = new byte[1024]; // short-lived object: garbage right after this loop turn
}
long after = totalCollections();
System.out.println("the collector ran while we created garbage: " + (after > before));
}
static long totalCollections() {
long total = 0;
for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
total += gc.getCollectionCount();
}
return total;
}
}
// Output:
// the collector ran while we created garbage: true
Finished this page? Track your progress (saved only in your browser).