Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory Management for local objects in java

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?

like image 896
Ankit Avatar asked Dec 15 '22 15:12

Ankit


2 Answers

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.

like image 74
kosa Avatar answered Jan 02 '23 20:01

kosa


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.

like image 21
Karthik T Avatar answered Jan 02 '23 18:01

Karthik T