This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

Question: In Javafinalize()When is the method called?

I created a test class that writes something to a file when finalize() is called. But the program was not executed. Why?

Answer a

The finailze() method is called when an object is about to be garbage collected. But even if the object has been treated as garbage, it is uncertain when it will be recycled.

Note that it is entirely possible that an object will never be garbage collected, and therefore will never call the Finalize () method.

  1. Object does not qualify for GC

Occurs when an object is always referenced and always accessible

  1. Meets gc criteria, but has not been garbage collected

This usually happens in simple test programs.

There are methods that allow the JVM to use finalize methods on methods that have not yet been called, but this is not a good idea either, because these methods do not guarantee that garbage collection will be performed.

You definitely can’t rely on Finalize to do the right thing, Finalize can only be used to clean up resources (usually non-Java resources). There is no guarantee that the Finalize method will be called on an object.

Answer two

protected void finalize(a) throws Throwable {}
Copy the code
  • Every class will start fromjava.lang.Object()inheritancefinalize()methods
  • This method is called when the garbage collector determines that there is no longer a reference to the object.
  • finalize()It does nothing by itself, but it can be overridden by any class.
  • This method is usually used to close non-Java resources, such as a file.
  • If rewrittenfinalize()It is best to usetry-catch-finallyStatement and always callsuper.finalize(). This is a security measure to ensure that you don’t forget to close the resource used to call the class object.
protected void finalize(a) throws Throwable {
     try {
         close();        // close open files
     } finally {
         super.finalize(); }}Copy the code
  • During garbage collection, any byfinalize()Any raised exception causes the collection to stop, but the exception is ignored.
  • finalize()You don’t call an object more than once.

Answer three

In general, it is best not to rely on the Finalize () method for any cleanup.

According to Javadoc:

When an object is not referenced anywhere, the garbage collector will collect the object as garbage.

If an object was always accessible, garbage collection would never happen.

Also, garbage collector is not guaranteed to execute at any particular time, unless you need to do something special with Finalize (), do not use this method.

The article translated from Stack Overflow:stackoverflow.com/questions/2…