1/4/12

Finalize(), Finally and Final in Java

There's some confusion in the mind of an intermediate level programmer about finalize(),finally and final in java. So to remove that confusion from each and everyone's mind I thought of writing a post on it.

finalize() :  A Method
finally : A Clause in Try-Catch
final :  Keyword in java


Finalize :


It is called by the garbage collecter on an object by garbage collection when it knows that there is no references on the object. The finalize() method is defined in the java.lang.Object class and its modifier is defined as protected. The finalize() method is not public  because it should only be invoked by JVM and not by anyone else and protected so that it can be overridden by the subclasses.

You can override the finalize() method and the declaration of the method should look like this :


protected void finalize() throws throwable

Ex.

The below class opens the file when constructed :


class OpenAFile {
    FileInputStream aFile = null;
    OpenAFile(String filename) {
        try {
            aFile = new FileInputStream(filename);
        } catch (java.io.FileNotFoundException e) {
            System.err.println("Could not open file " + filename);
        }
    }
}

As a part of good programming practice, the open file should be closed :


protected void finalize () throws throwable {
    if (aFile != null) {
        aFile.close();
        aFile = null;
    }
}

It is important to understand that finalize() is only called just prior to garbage collection. It is not called when an object goes out-of-scope, for example. This means program should provide other means of releasing system resources, etc., used by the object. It must not rely on finalize() for normal program operation.



Finally : 



The finally clause defines a code that always executes, regardless of whether the exception was caught. The following sample code is taken from the book by Frank Yellin:


try {
  startFaucet();
  waterLawn();
} catch (Exception e) {
  logProblem(e);
} finally {
  stopFaucet();
}

In the above example the Faucet is turned off regardless of whether the exception was caught or not. The code inside the braces after try is called the protected code.


The only thing that stop finally from executing are virtual machine shutdowns i.e. System.exit method etc. 

Final :


Read Detailed explanation about final keyword in Java.

SHARE THIS POST:

3 comments:

  1. This is a very popular Java questions and still asked both at junior and mid senior level. Thanks for covering it.

    Javin
    Top 20 Core Java Interview questions answers

    ReplyDelete
  2. Maybe for your next post you can explain why it's stupid to close input streams in a finalizer.

    ReplyDelete
  3. it's definitely not the best idea to close input streams in a finalize method

    ReplyDelete