Card 06/ 09

GotchaDifficulty: Advanced1 min

Why System.gc() Is a Suggestion

A batch job calls System.gc() between files to keep memory down. The heap graph is unchanged and the job is measurably slower than it was.

java
for (Path file : files) {
    process(file);
    System.gc();
}

System.gc() is a request, and the specification says so: it suggests that the virtual machine spend effort on collection. Whether anything happens, when it happens and how much is collected are all decisions the collector keeps.

What the call does and does not do
DoesDoes not
Suggest a collectionGuarantee one runs
Sometimes trigger a full collection, which pauses every threadFree memory that is still reachable
Cost time, reliablyFix a leak

If memory is growing, the objects are reachable and no collector can take them. The call cannot help, because the thing it asks for is already happening whenever it can. Find what is still holding them instead — which is the next card's whole subject.