Memory Management for local objects in java

2019-05-07 04:15发布

问题:

If I have a method inside a class and I am creating an object inside that method then would that object be destroyed and the memory allocated to it released once the method is finished?

eg. -

public void drawFigure(){

    Paint paint = new Paint();
    paint.setSomeProperty();

    canvas.drawLine(startPoint, finishPoint, paint);

}

So after the method drawFigure is complete, paint object will be destroyed ? which same as paint = null, but I do not need it to be set to null, because it is a local object. Am I right?

回答1:

It is not guaranteed that object will be GCed as soon as method call is done, but object will become as eligible for GC and on next GC run it may be collected and memory will be free.

EDIT:

Yes you are correct. You don't need to set it to null. Local variables will be created on stack and stack will be removed as soon as method is completed. So, paint will go away from memory and new Paint() object will be on heap without any references, which makes above object as eligible for GC.

See this youtube video by Standford professor.



回答2:

Depends on if you mean create an object using new or if you mean create a reference.

public AnObjectType GimmeAnObject(){
    AnObjectType object = new AnObjectType ();
    return object;
}

This would destroy the reference object but the memory allocated is returned from the function and will only be deallocated (marked eligible for GC) if the return value is not assigned to another reference at the call site.

Edit: In your example, the paint reference will be destroyed. If the drawLine method does not keep a reference to paint (unlikely to) the object itself will be eligible for garbage collection when paint is destroyed.

So yes, it is exactly as if you called paint = null as the last line of the function.



回答3:

As long as a reference to the object does not escape the method (i.e. you don't return the object or return an object that references the object.)

The timing of the release of the memory is up to the garbage collector, but the object referenced would be available for collection.



回答4:

Are you returning reference to that created object? if so then it will be the subject of Garbage Collector interest after you release all references to that object. If not then it might be the point of interest of GC immediately after you step out that function. Nevertheless GC is not clearing this object immediately, and you can't control this. you never know when GC will destroy such an object. it is Virtual machine problem to relase those resources.



回答5:

the local reference variable paint will become out of scope, then the object in memory has no reference to it ( its eligible to GC) so this memory will collected by GC in the next GC running cycle.



回答6:

Yes sir, because local variables are stored on the stack