0

Where we need to override finalize() method in java when we don't have idea when finalize() method for any given object might be run?What type of resources we can close in finalize()?What is the best chances when GC will called finalize() method?

  • 1
    Could be a doublicate to this one [http://stackoverflow.com/questions/2506488/java-finalize-method-call](http://stackoverflow.com/questions/2506488/java-finalize-method-call) – Akunosh Jun 28 '13 at 19:50
  • This is a three-in-one question. The answer could be a monograph. – zw324 Jun 28 '13 at 19:56
  • We don't because a resource should be closed as soon as you're done using it and we can't tell when exactly finalize() would get called. – Ravi K Thapliyal Jun 28 '13 at 20:02
  • 1
    One reason for providing a finalizer could be to identify objects which was not closed correctly in your code (by keeping track). I.e. not a tool for programming but for debugging. – Thorbjørn Ravn Andersen Jun 29 '13 at 23:19

4 Answers4

1

You should override finalize when your class has resources that won't be cleaned up by the GC, such as file handles or database connections. These resources should be cleaned up in the application code since, as you said, we don't have any idea when finalize will be run, however it's a good idea to also clean up these resources in the finalizer in case the programmer screwed up and left the resources open (if the resources are still open when finalize runs then log this as a warning or as an error since this means that the application code isn't cleaning up resources correctly).

.NET lets you suppress the finalizer if the programmer correctly cleaned up the object's resources by e.g. calling dispose, but unfortunately I don't think that Java allows for an analogous pattern.

Zim-Zam O'Pootertoot
  • 17,888
  • 4
  • 41
  • 69
  • we can do same thing in finally block also.then why do it in finalize() method.any real context where it fits? – Jaikant Bhagwan Das Jun 28 '13 at 19:52
  • 1
    @Jaikant Bhagwan Das The problem is that a programmer might forget to clean up the resources in a `finally` block. The pattern I've most frequently seen for an overridden `finalize` method is to check to see if the object's resources are still open - if they're open, then close them, and log it as an error since this means that somewhere in the program the resources aren't being cleaned up properly. Then the finalizer is sometimes commented out when the program is released to production if it's causing performance problems. – Zim-Zam O'Pootertoot Jun 28 '13 at 19:56
  • It is really never a good idea to implement `finalize` except, as you note, for debugging. If there's a resource leak, it must be removed, and not left to `finalize` to take care of. – Marko Topolnik Jun 28 '13 at 20:31
  • @MarkoTopolnik Until the fix, `finalize()` can save the system from crashing in production. Of course, you should put some high-severity log into it. This is less for deterministic behavior, but more for good old double-safety. – Dávid Horváth Aug 21 '20 at 11:08
1

it's best to close resources in a close method that you call manually. finalize only gets called when the object is being garbage collected, which might not be until long after you are done using the object.

The only reason I have ever overridden finalize was to debug memory usage in my app where some objects weren't getting collected.

Rocky Pulley
  • 22,531
  • 20
  • 68
  • 106
1

Firstly,The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup, before the object gets garbage collected.
For example, Closing an opened database connection.

The finailze() method should be overridden for an object to include the clean up code or to dispose of the system resources that should to be done before the object is garbage collected.

About What is the best chances when GC will called finalize() method?, There are two ways in which we can request the JVM to execute the Garbage Collection:

  1. Runtime.getRuntime().gc();
  2. System.gc();

What type of resources we can close in finalize(), the answer is in two situation:

  1. Set all availabel object references to null after the purpose of creating the object is done.

  2. Make the reference variable to refer to another object: Decouple the reference variable from the object and set it refer to another object, so the object which it was referring to before reassigning is eligible for Grabage Collection.

Azad
  • 5,047
  • 20
  • 38
  • Closing of Database connection we can also perform in finally block?why i depend on finalize () method. – Jaikant Bhagwan Das Jun 28 '13 at 20:00
  • 1
    @JaikantBhagwanDas: finally block is to be executed after the try or try-catch, it's created for special purposes, but the GC doesn't care if there is a finally block or not, it will be available when an object is eligible to be Grabaged. – Azad Jun 28 '13 at 20:05
0

From my notes:

Methods named finalize() are called before the object is garbage-collected. There is no need to free any objects, but some other resources (e.g. open file descriptors) may need to be freed.

protected void finalize() {
    if( fd != null ) {
        try {
            closeIt() ;
        } catch (IOException e) {
            // print an error something, or otherwise try to recover
        }
    }
}

Theoretically, a finalizer might do something to prevent an object from being garbage-collected (e.g. store "this" in some reference). This is never a useful thing to do.

Unlike constructors, finalizers are not automatically chained. It's a very good idea to chain them manually, preferably at the end of the finalizer:

protected void finalize() {
    // free resources consumed by this class
    // chain upward:
    super.finalize() ;
}

For the most part, you almost never need to write a finalizer().


Edit: an earlier version of this answer declared finalize() as throwing IOException. In retrospect, that's probably a very bad idea; I don't know what I was thinking.

Edward Falk
  • 9,991
  • 11
  • 77
  • 112