Reputation: 2940
I know java GC can destroy an object on the heap if the reference variable that points to the object is manually set to null or set to point to another object:
TestObject test = new TestObject();
test.dosomething();
test = null;
My question is that if I did not give that object a name (reference variable) when I created it, how do I free the memory that object occupies after I'm done with the object:
(new TestObject()).dosomething();
Will this object live on the heap forever before the program ends?
Upvotes: 5
Views: 2107
Reputation: 280171
I'm going to explain this through byte code. First thing to note is that while a reachable reference exists to an object, that object cannot be collected. A important aspect of this is that if a reference value is on the stack in a method's stack frame, the object being referenced is accessible. It therefore cannot be garbage collected.
Compile the following program
public class Example {
public static void main(String[]args) {
new Example().sayHello();
}
public void sayHello() {}
}
Running javap -c Example
will give you something like
public static void main(java.lang.String[]);
Code:
stack=2, locals=1, args_size=1
0: new #2 // class Example
3: dup
4: invokespecial #3 // Method "<init>":()V
7: invokevirtual #4 // Method sayHello:()V
10: return
A index 0
, the new
byte code instruction, creates a new object and pushes the reference to that object onto the stack. The dup
instruction copies that value and pushes it on top of the stack. So you now have two references to that object. invokespecial
uses one, invokevirtual
uses the other (they pop the reference value they use). Once that is done, there are no more references to the object and it can be garbage collected.
For reference, here are the byte code instructions.
Upvotes: 1
Reputation: 30578
After you create the object with new
and call the method dosomething()
on it there are no references left to it so it becomes eligible for garbage collection.
Even if you create two objects which point to each other with references and they no longer have a connection to the root reference they will become eligible to gc as well (the jvm can detect this circular reference without root connection).
So to answer your question: No that object in your second example will be gc-ed after you call dosomething
on it.
Just a note: In practice you don't need to null
your references (I actually nearly never do it) it is enough if you keep them in local scope so when you leave it the local variables get cleaned up.
Upvotes: 6