Set null object reference or call finalize () method?

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

For instance,

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

Since im is done using 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. embarrassed me. Does this mean that even if I use it, it wonโ€™t do anything at all if the GC decides to do it? Then, will my decision to install obj for zero help?

This all presupposes his big project, and the scope has not yet ended for GC to free her. Thanks.

+5
source share
2 answers

NEVER call the finalize() method of an object manually. This is used only for a virtual machine. The VM will call it at the appropriate time (as part of the garbage collection process).

You can set the reference variable to null to make the object suitable for garbage collection earlier than otherwise, but this does not immediately terminate GC'd. (Note that the assignment operator uses the = ; == operator - a relational operator to verify the equality of its operands.)

If your object maintains the state that you want to ensure, it is cleared on demand and then implements another method for it. close() is a popular name for such methods. It is recommended to avoid finalize() implementation, if at all possible. The GC will automatically take care of most of the resources that you probably want to clear manually in finalize() .

+1
source

None. If obj no longer used in the code (and does not refer to the same object as obj ), the object will no longer be accessible and will become a candidate for garbage collection.

Configuring obj - null will not do anything (YMMV depending on the implementation of garbage collectors).

Regarding the call to finalize() , no need. Let the garbage collector take care of this. But note that finalize is a method like any other. What you quote indicates that the GC will not call it more than once, no matter how many times your code has called it.

+7
source

Source: https://habr.com/ru/post/1210583/


All Articles