Finalize() cleanup vs. Garbage Collector removing an object from memory

Chris Okyen picture Chris Okyen · Jun 16, 2012 · Viewed 9.5k times · Source

I was reading about the finalize() method and was curious:

What is the difference between the task of cleaning up objects ( setting them to NULL ) in finalize, and removing an object from memory?

Answer

stefan bachert picture stefan bachert · Jun 16, 2012

What is the difference between the task of cleaning up objects ( setting them to NULL ) in finialize

setting to null removes ONE reference to the object. if NO more references to an object exists, the garbage collector is allowed (not required) to remove the object

and removing an object from memory?

there is NO explicit way in java to remove (destroy, delete) an object. The garbage collector will do it when he likes. Especially the time from removing the last reference to remove/destroy the object is indefinite

There is NO need to set references to null in finalize method. when the garbage collector call finalize the objects and its references will gone soon anyway.

I never wrote an own finalize method during my very long java experience.

The rare occasion in which it make sense to wrote an own finalize method appear if your object is dealing with os-resources. However, in general you use standard packages for os accesss