Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java GC destroy objects if instance variables still have reference?

I've read through some of the Java garbage collection guides online, but I'm still a bit unclear and wanted to make sure so that I don't have memory leaks in my code.

Does Java GC collect objects that lost its reference, but its variables still have reference?

So let's say I have SomeObject:

public class SomeObject {
    public ObjectVar var;

    public SomeObject() {
        var = new ObjectVar();
    }
}

And my code:

SomeObject obj1 = new SomeObject();
SomeObject obj2 = new SomeObject();
obj2.var = obj1.var;
obj1 = null;

So obj1's var has reference, but obj1 no longer has any reference. So, will the GC destroy obj1, but keep var alive? (I'm assuming so; just wanted to make sure). Thanks!

like image 269
baekacaek Avatar asked May 16 '13 23:05

baekacaek


2 Answers

Here is what is going to happen (see comments below)

// obj1 and obj1.var get created
SomeObject obj1 = new SomeObject();
// obj2 and obj2.var get created
SomeObject obj2 = new SomeObject();
// old obj2.var becomes eligible for GC
obj2.var = obj1.var;
// obj1 becomes eligible for GC
obj1 = null;

In the end, two objects remain that do not get GCd - obj2 and the former obj1.var which is now referenced as obj2.var.

Note: In a special case of ObjectVar class being a non-static inner class of SomeObject, keeping a reference to obj1.var would also keep obj1 around. This is because internally the SomeObject.ObjectVar class has a hidden variable of type SomeObject, which references the outer object of the inner class.

like image 165
Sergey Kalinichenko Avatar answered Oct 22 '22 11:10

Sergey Kalinichenko


Yes of course.

Remember, what you store in the var field is actually reference to the object, not the object itself. So when GC collects obj1, the var object is untouched (must not be touched), especially since it has a reference from obj2, which is still alive and well..

like image 38
zw324 Avatar answered Oct 22 '22 13:10

zw324