The Finalize Method Tutorial

In my Garbage Collection tutorial, I discussed how Java uses the garbage collector to free up memory on the heap. Objects are stored in the heap memory and they become eligible for cleanup when they no longer have an active reference. There are occasions when you will need to perform some sort of action when an object is about to be destroyed. Luckily, Java provides a method for doing just that, it is called the finalize() method. Unluckily, it is important to understand that the finalize() method cannot be relied upon to actually execute ... I'll explain later in this tutorial. To implement the finalize method you simply need to add it into your class, its structure looks like this:
protected void finalize() {
      Statements are executed here if finalize() is actually invoked.
}

Don't worry about the protected keyword yet, I will discuss what purpose it serves in a future tutorial.



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md FinalizeMethod
C:\Java>cd FinalizeMethod
C:\Java\FinalizeMethod>Notepad FinalizeMethod.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


class FinalizeMethod {
    public static void main(String args[]) {
        for (int i = 0; i < 6; i ++) {
            new Box();
        }
    }
}
class Box {
    Box() {
        super();
        System.out.println("This object reference is located on the heap at: " + this);
    }

    protected void finalize() { // don't worry about protected yet
        System.out.println("!!!Finalized!!! " + this );
    }
}

Now switch back to the command prompt (CMD) and type in javac FinalizeMethod.java and press Enter.
Now type in java FinalizeMethod and press Enter.


C:\Java\FinalizeMethod>javac FinalizeMethod.java
C:\Java\FinalizeMethod>java FinalizeMethod
This object reference is located on the heap at: Box@659e0bfd
This object reference is located on the heap at: Box@2a139a55
This object reference is located on the heap at: Box@15db9742
This object reference is located on the heap at: Box@6d06d69c
This object reference is located on the heap at: Box@7852e922
This object reference is located on the heap at: Box@4e25154f

What went wrong, how come we didn't see the the finalize() method execute? Finalize() is not called when an object is no longer in scope, finalize is called just prior to garbage collection. Because of this, your program should utilize other methods of executing statements that need to be run before the object is destroyed. Things like closing file handles, freeing up resources, etc., should not depend on finalize() for normal program execution. As I stated in my garbage collection tutorial, we have no way of knowing when the garbage collector is going to run. In this case, the garbage collector ran sometime after the completion of my main method, so the string literal "!!!Finalized!!! " could not be displayed to the console.
In order to demonstrate the finalize() method, I will make an infinite loop that creates an object on every iteration. Hopefully, we will see some "!!!Finalized!!! " roll across the console. Note: you can press CTRL+C to terminate the loop at any time.


class FinalizeMethod {
    public static void main(String args[]) {
        while (true) {
            new Box();
        }
    }
}
class Box {
    Box() {
        super();
        System.out.println("This object reference is located on the heap at: " + this);
    }
    protected void finalize() { // don't worry about protected yet
        System.out.println("!!!Finalized!!! " + this );
    }
}

Now switch back to the command prompt (CMD) and type in javac FinalizeMethod.java and press Enter.
Now type in java FinalizeMethod and press Enter.


C:\Java\FinalizeMethod>javac FinalizeMethod.java
C:\Java\FinalizeMethod>java FinalizeMethod
...
...
This object reference is located on the heap at: Box@3610b408
!!!Finalized!!! Box@6be865c1
This object reference is located on the heap at: Box@5fb99e3d
!!!Finalized!!! Box@6ba543a2
!!!Finalized!!! Box@136a5572
!!!Finalized!!! Box@65d3e2ba
!!!Finalized!!! Box@3299e315
This object reference is located on the heap at: Box@194971bd
!!!Finalized!!! Box@4ab1693b
!!!Finalized!!! Box@5295a774
...
...


Final thoughts

I just want to reiterate that finalize() is not called when an object is no longer in scope, finalize is called just prior to garbage collection. Because of this, your program should utilize other methods of executing statements that need to be run before the object is destroyed. Things like closing file handles, freeing up resources, etc., should not depend on finalize() for normal program execution. The bottom line is this ... don't put code into the finalize() method that you absolutely need to have executed.


Tutorials