The Garbage Collector is a "task" that periodically scans your objects to detect what is not in use (in reality it is a mechanism to emulate a machine with an infinite memory).
For this reason, when you are holding a reference to an object instance you no longer need, you must set it to null
in order to let the Garbage Collector know that you are no longer interested in that instance (and possibly its descendants).
This does not mean that you have to set every variable to null
after use, but you have to watch for fields.
As Java does not have a dispose pattern (see here for more information), you have to design your APIs to mimic it: when you are finished using an object instance which holds a reference you want to free, you have to add an appropriate method to perform such action.
Consider the following example:
class MyClass1
{
int Field1;
int Field2;
int Field3;
int Field4;
}
class MyClass2
{
private MyClass1 m_MyReference;
public MyClass2()
{
m_MyReference = new MyClass1();
}
public void DoSomething()
{
// do something here that uses m_MyReference.
}
}
If an instance of MyClass2 is held but some other reachable instance of your program (e.g. a singleton, or some instance currently in the stack), you will never release the memory associated to MyClass1 as it is still referenced by m_MyReference
.
Is this bad? It depends on that MyClass2 and MyClass1 are truly doing.
If you know that MyClass2 could have a very long lifespan and you want to retain the reference to MyClass2 but to release the memory associated to MyClass1, you have to do something similar to the code below:
class MyClass2
{
private MyClass1 m_MyReference;
public MyClass2()
{
m_MyReference = new MyClass1();
}
public void DoSomething()
{
// do something here that uses m_MyReference.
}
public void Dispose()
{
m_MyReference = null;
}
}
This way you expose to the caller a way to signal that you are no longer holding a reference to instances you do not need.
Remember that simply assigning null
to a variable or field, does not automatically release the memory. The Garbage Collector is asynchronous and runs when it decides so.
Hope to have given the idea without going too deeper.