Reputation: 452
Why finalize() method in java is not in Finalizer class? Why it is defined in Object Class?
Upvotes: 2
Views: 179
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
Reputation: 121649
The "Finalizer" class, java.lang.ref.Finalizer and the "finalizer()" method, java.object.finalize are two separate, distinct things.
As alexey noted about "finalize()",
You can override [finalize()] ... to specify what to do when a given object is collected by garbage collector.
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).
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).
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