No, it means the programmer has not released all references to the object.
Say for instance I made a class like this:
Code:
public class VeryLargeObject {
public byte[] lotsOfData = new byte[10241024];
}
And then another class that did something with them:
Code:
public TestClass {
public VeryLargeObject[] objects = new VeryLargeObject[10];
public TestClass() {
for(int i = 0; i < objects.length; i++) objects[i] = new VeryLargeObject();
}
}
And then wrote a piece of code like this:
Code:
public static void main(String[] args) throws InterruptedException {
TestClass test = new TestClass();
while(true) {
// doing something with TestClass to ensure it doesn't get optimized away
System.out.println(test.getClass());
Thread.sleep(10000L);
}
}
Because there are still references to the object, the garbage collector will not delete it and it will take up memory.
The garbage collector will do its best to delete objects if you need more memory (i.e. when the heap space runs out, and you try to allocate more memory, it'll try to delete unused memory), or when System.gc() is called and I also think it does it on a schedule in most VMs.
However, the problem Gnarly is talking about, is where you accidently leave references to an object. Like in the example above, the objects array could still be accessed, so the garbage collector does not delete it and it sits there taking a lot of memory.
You can ensure this doesn't happening by setting references to an object to null where appropriate. However *this does not need to be done all the time* (and some code here does it too much).
For instance, say you had this method:
Code:
public void doSomething() {
Object o = new Object();
// now do some stuff
}
You do not need to set o to null at the end, because the reference is lost when the method exists anyway.
The same goes for a class like this:
Code:
public class MyClass {
public Object someObject = new Object();
}
If you had some code that used it like this:
Code:
MyClass class = new MyClass();
// now do something
At the end many people here would write
Code:
class.someObject = null;
class = null;
However, in this case, it is not necessary and you just need to do
What you do need to be wary of is:
- references of an object in others that are not going to be garbage collected
- references of an object in collections in other classes/instances of that class - needs to be removed from the collection otherwise a reference remains and it will not be garbage collected.
- probably more situations, you just get to know the best way of doing this with experience.