Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set object reference to null or call the finalize() method?

As a java beginner I wanted to ask about if I should set an object reference to null, or call the finalize method in a large project?

For example,

while( obj... some code here){
 //code stuff
}
obj = null; // or obj.finalize();

Since im done with the obj and there are no more references to it what should i do with it? set it to null or call finalize();?

I read the java doc but this paragraph The finalize method is never invoked more than once by a Java virtual machine for any given object. confused me. Does that mean that even if i use it, it won't do anything at all unless GC decides to do so? Then, will my decision to set the obj to null help any?

This all assuming its a large project and the scope has yet to end in order for GC to deallocate it itself. Thanks.

like image 504
Voqus Avatar asked Jan 07 '15 17:01

Voqus


People also ask

What is the finalize () method in object class?

The Finalize method is used to perform cleanup operations on unmanaged resources held by the current object before the object is destroyed. The method is protected and therefore is accessible only through this class or through a derived class.

Which one is correct for the finalize () method?

The finalize method is called when an object is about to get garbage collected. That can be at any time after it has become eligible for garbage collection. Note that it's entirely possible that an object never gets garbage collected (and thus finalize is never called).

Can I set an object to null Java?

In Java, a null value can be assigned to an object reference of any type to indicate that it points to nothing. The compiler assigns null to any uninitialized static and instance members of reference type. In the absence of a constructor, the getArticles() and getName() methods will return a null reference.

What does finalize () do?

Overview. Finalize method in Java is an Object Class method that is used to perform cleanup activity before destroying any object. It is called by Garbage collector before destroying the object from memory. Finalize() method is called by default for every object before its deletion.


1 Answers

Neither. If obj is no longer used further in the code (and nothing else references the same object as obj does), the object will no longer be reachable and will become a candidate for Garbage Collection.

Setting obj to null will not achieve anything (YMMV depending on implementation of garbage collectors).

As for calling finalize(), don't. Let the Garbage Collector take care of that. But note that finalize is a method like any other. What the text you quoted is saying is that the GC will not call it more than once, regardless of the amount of times your code may have invoked it.

like image 193
Sotirios Delimanolis Avatar answered Sep 20 '22 17:09

Sotirios Delimanolis