Card 06/ 09
All 9 cards
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.
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.
| Does | Does not |
|---|---|
| Suggest a collection | Guarantee one runs |
| Sometimes trigger a full collection, which pauses every thread | Free memory that is still reachable |
| Cost time, reliably | Fix 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.
- Java
- Garbage Collection
- Performance