Bikramjit Rajbongshi
Bikramjit Rajbongshi

Reputation: 452

Why finalize() method in java is not in Finalizer class? Why it is defined in Object Class?

Why finalize() method in java is not in Finalizer class? Why it is defined in Object Class?

Upvotes: 2

Views: 179

Answers (2)

alexey
alexey

Reputation: 622

Look at javadoc about the method finalize()

Called by the garbage collector on an object (that object may be any object that is why it's declared in the object class and not in the finalizer class) when garbage collection determines that there are no more references to the object.

You can override this method on any classes to specify what to do when a given object is collected by garbage collector.

Upvotes: 3

paulsm4
paulsm4

Reputation: 121649

  1. The "Finalizer" class, java.lang.ref.Finalizer and the "finalizer()" method, java.object.finalize are two separate, distinct things.

  2. As alexey noted about "finalize()",

You can override [finalize()] ... to specify what to do when a given object is collected by garbage collector.

  1. The purpose, role and lifetime of the "Finalizer class" is discussed here:

http://www.fasterj.com/articles/finalizer2.shtml

The JVM will ignore a trivial finalize() method ... Otherwise, if an instance is being created, and that instance has a non-trivial finalize() method defined or inherited, then the JVM will do the following:

  • The JVM will create the instance

  • The JVM will also create an instance of the java.lang.ref.Finalizer class, pointing to that object instance just created (and pointing to a queue that it will be put on by the GC)

  • The java.lang.ref.Finalizer class holds on to the java.lang.ref.Finalizer instance that was just created (so that it is kept alive, otherwise nothing would keep it alive and it would be
    GCed at the next GC).

  1. So to answer your question: "finalize()" is something YOU do (to customize the cleanup behavior of your object during GC); "Finalize" is an object the JVM creates (to facilitate and manage that cleanup).

  2. For many reasons, including both performance and security, it's generally a bad idea to create your own, custom finalizer unless you absolutely have to.

Upvotes: 3

Related Questions