Video in progress
Does setting a local variable to null after you are done with it help the GC?
Usually not. The JIT knows after which point a variable is no longer used and can treat the object as "dead" even before that. Setting null makes sense only for long-lived fields or collection elements.
📖 Answer
This habit is left over from C/C++ or very old Java. For example:
void importFile(Path path) {
byte[] data = Files.readAllBytes(path);
List<Row> rows = parse(data);
data = null; // almost always useless
save(rows);
}
In JIT-compiled code, the "liveness" of data ends at its last use. The GC can collect it during save() even if you don't set it to null. In interpreter mode this isn't always the case, but hot code goes through the JIT anyway.
Where null is really needed:
- in a collection you wrote yourself:
elementData[--size] = nullinsideArrayList.removeis there for exactly this reason, otherwise the array would hold on to the old object; - in the field of a long-lived object, if it holds big data that is no longer needed;
- in static fields.
A better solution than that is to keep the variable's scope small: move the work with the big data into a separate method. When the method ends, the reference disappears on its own.
Sign up to mark studied questions and save your progress.