Search code examples
javamemory-leaksmulti-layer

Java memory leaks with classes


I am wondering if the following piece of code is a memory leak, since Google is only turning up weird examples. Basically, if I have a class Tree:

public class Tree{

     private Bird[] birds;

     public Tree(){
          birds = new Bird[100];
     }

}

and I hold a class reference to a Tree like this:

Tree myTree = new Tree();

and then shortly afterwards I set that reference to null:

myTree = null;

Will all the 100 allocated Birds be taken care of WITH the tree class by the garbage collector? Or do I need a delete() method? I know Java doesn't have destructors but still this multi-layer class example confuses me:

inside Tree.java:

public void deleteBirds{
     birds = null;
}

Solution

  • Will all the 100 allocated Birds be taken care of WITH the tree class by the garbage collector?

    Well, your code doesn't actually create any instances of Bird. It just creates an array, and every element of that array will be null to start with.

    However, the basic answer is "yes" - if you nothing else has a reference to the array, and nothing else has a reference to any of the Bird objects that you might create elsewhere, then the garbage collector will take care of them. You almost certainly shouldn't write any kind of "delete" method.

    You probably don't need your myTree = null; statement either... if it's a local variable going out of scope, or an instance variable in an object which is going to become eligible for garbage collection anyway, then it's pointless.

    It can take a while for relatively new Java programmers to learn to trust the garbage collector, and let go of control... but once you do so, your code will be a lot simpler :)