Does assigning objects to null in Java impact garbage collection?

Typically, no.

But like all things: it depends. The GC in Java these days is VERY good and everything should be cleaned up very shortly after it is no longer reachable. This is just after leaving a method for local variables, and when a class instance is no longer referenced for fields.

You only need to explicitly null if you know it would remain referenced otherwise. For example an array which is kept around. You may want to null the individual elements of the array when they are no longer needed.

For example, this code from ArrayList:

public E remove(int index) {

    E oldValue = (E) elementData[index];

    int numMoved = size - index - 1;
    if (numMoved > 0)
         System.arraycopy(elementData, index+1, elementData, index,
    elementData[--size] = null; // Let gc do its work

    return oldValue;

Also, explicitly nulling an object will not cause an object to be collected any sooner than if it just went out of scope naturally as long as no references remain.


void foo() {
   Object o = new Object();
   /// do stuff with o


void foo() {
   Object o = new Object();
   /// do stuff with o
   o = null;

Are functionally equivalent.

Leave a Comment