Sub topic 4
How Collectors Reclaim Memory
Assume you know basic Java syntax, objects, references, and how to run a Java program from the command line. This chapter focuses on the algorithms the JVM uses after it decides that heap memory should be reclaimed.
Garbage collection has two main goals:
- Find objects that the program can no longer reach.
- Make the memory occupied by those objects available for new allocations.
A collector must also balance throughput, pause time, and memory overhead. Throughput is the amount of application work completed over time. Pause time is how long application threads are stopped while collection runs.
The basic collection cycle
Most collectors perform some variation of these steps:
- Start from garbage-collection roots, such as active thread stacks, static fields, and JNI references.
- Follow references from those roots.
- Mark every reachable object as live.
- Reclaim or reorganize the memory belonging to unmarked objects.
- Resume normal allocation.
The exact timing differs between collectors. Some stop all application threads. Others perform much of the work concurrently while the application continues.
Mark-sweep
Mark-sweep is the simplest strategy.
During the mark phase, the collector identifies every reachable object. During the sweep phase, it releases memory occupied by objects that were not marked.
Mark-sweep does not usually move live objects. This makes it relatively simple and avoids updating references to moved objects. Its main weakness is fragmentation. A heap can contain enough total free memory for an allocation but lack one sufficiently large contiguous region.
| Strategy | What happens to live objects | Main benefit | Main cost |
|---|---|---|---|
| Mark-sweep | They remain where they are | Low movement overhead | Fragmentation |
| Mark-compact | They move together | Large contiguous free area | Longer pauses and reference updates |
| Copying | They move to another region | Fast allocation and low fragmentation | Requires spare space |
Mark-compact
Mark-compact starts with marking, then moves live objects toward one end of a memory region. The collector updates references so they point to the objects' new locations. The unused space becomes one contiguous area.
Compaction prevents fragmentation, which helps when the application needs large objects. However, moving objects and updating references takes work. If application threads are stopped during this work, the pause can be noticeable.
Copying collection
A copying collector divides a region into areas. It copies live objects from one area into another and then treats the original area as completely free.
Allocation becomes fast because the collector can use a simple pointer to the next free address. Copying also removes fragmentation automatically. The trade-off is that the destination area must have enough space for the live objects. Copying is most effective when only a small portion of the source area is still live.
Choosing the trade-off
No single algorithm is best for every workload.
- Use mark-sweep when avoiding object movement matters more than fragmentation.
- Use mark-compact when contiguous free space is important and longer pauses are acceptable.
- Use copying when most objects die quickly and the live set is small.
- Use a generational design when the workload creates many short-lived objects. It applies collection effort more often to areas where garbage is likely to be found.
This program creates temporary objects. Most arrays become unreachable after each loop, so a collector can reclaim them during later collections.
public class AllocationPressure {
public static void main(String[] args) {
long total = 0;
for (int batch = 0; batch < 100; batch++) {
for (int item = 0; item < 10_000; item++) {
byte[] temporary = new byte[1024];
total += temporary.length;
}
}
System.out.println("Allocated approximately " + total / (1024 * 1024)
+ " MB of temporary data.");
}
}You can run it with GC logging enabled:
javac AllocationPressure.java
java -Xlog:gc AllocationPressureThe log shows when collections occur, but it does not directly prove which algorithm reclaimed each object. Collector-specific logs and metrics are needed for detailed analysis.
Exercise
Why can mark-sweep leave an allocation failure even when the heap has enough total free memory?
Show answer
It can leave free memory in many small, separated gaps. A large object needs one contiguous region, so fragmentation can prevent the allocation.