ss1
ss1

Reputation: 1191

How does the Garbage Collector in Java handle variables inside a POJO?

I'm currently trying to fix a memory leak in my program and my brain starts to throw OutOfOptions Exceptions. The program creates a lot of objects and I dereference them with object = null as soon as they aren't needed any more, but somehow the memory usage keeps still growing over time. Now I'am asking myself if I have to dereference variables inside an object as well.

For example:

public class Pojo {

    private String foo;
    private Integer bar;
    private AnotherPojo anotherPojo;

    public Pojo(String foo, Integer bar, AnotherPojo anotherPojo) {
        this.foo = foo;
        this.bar = bar;
        this.anotherPojo = anotherPojo;
    }

}
// ...
Pojo pojo = new Pojo("foo", 123, new AnotherPojo())
// ...

Is it enough to do pojo = null or do I also have to dereference every variable separately in the Pojo object?

Upvotes: 0

Views: 157

Answers (1)

Zim-Zam O'Pootertoot
Zim-Zam O'Pootertoot

Reputation: 18148

You only need to null the pojo reference, not the references held in the pojo.

The garbage collector traces from the program roots to find potentially live objects, where the roots are generally the references on the stack i.e. the references in a method invocation. If an object is not reachable from the roots, then none of the objects referenced by that object are transitively reachable through that object, although the referenced objects may be directly reachable via the roots or through another chain of objects that's reachable through the roots. But if an object isn't reachable because you've nulled out all references to it then it doesn't matter what other objects are referenced by the object (including self references), because these references won't be traced by the garbage collector - hence you don't need to null the references held by the object.

If you haven't already done so, then I recommend using something like Eclipse's memory analyzer to help you figure out where the leak is occurring.

One memory leak scenario is that you've got a Big Collection Full Of Everything that is making objects reachable even after they're nulled out everywhere else in the program; in this case your options are to remove mostly-dead objects from these data structures, or if this isn't practical/feasible you can fill the collection with WeakReferences or SoftReferences - these tell the garbage collector "it's fine to reclaim an object if the only references held to it are weak or soft" (weak references are typically collected more eagerly than soft references). If the Big Collection is a map then Java provides a WeakHashMap that you can use instead.

Upvotes: 1

Related Questions