final-finalize-finally

Explain the difference between final, finalize and finally

final / final modifier

  1. A Java keyword. You define an entity once and cannot change it or derive from it later.
  2. More specifically: a final class cannot be subclassed, a final method cannot be overridden and a final variable cannot change from its initialized value. The final modifier keyword makes that the programmer cannot change the value anymore.
  3. The actual meaning depends on whether it is applied to a class, a variable, or a method.
    1. final Classes- A final class cannot have subclasses.
    2. final Variables- A final variable cannot be changed once it is initialized.
    3. final Methods- A final method cannot be overridden by subclasses.

There are two reasons for marking a method as final:

  1. Disallowing subclasses to change the meaning of the method.
  2. Increasing efficiency by allowing the compiler to turn calls to the method into inline Java code.

finalize

finalize() method is used just before an object is destroyed and can be called just prior to garbage collection. The JVM calls it as a part of the garbage collection process.

finalize() method get invoked when JVM figures out that this particular instance should be garbage collected.

The main purpose of the finalize() method is to release resources used by objects before they’re removed from the memory. A finalizer can work as the primary mechanism for clean-up operations, or as a safety net when other methods fail.

Examples of clean-up activities: closing the resources associated with that object like Database Connection, Network Connection, or we can say resource de-allocation.

The Garbage collector calls the finalize() method only once on any object. Once the finalize() method completes immediately, Garbage Collector destroys that object.

protected void finalize throws Throwable{}

Java Object class contains the finalize() method. So, finalize() method is available for every java class since Object is the superclass of all java classes. Since it is available for every java class, Garbage Collector can call the finalize() method on any java object.

The finalize method, which is present in the Object class, has an empty implementation. In our classes, if clean-up activities are needed, then we have to override this method to perform the clean-up activities.

import java.lang.*;

public class Demo {

        // Driver code
        public static void main(String[] args) throws Throwable {
                // Creating demo's object
                demo d = new demo();

                // Calling finalize of demo
                d.finalize();
        }

        protected void finalize() throws Throwable {
                try {
                        System.out.println("inside Demo's finalize() method");
                        // code to clean-up resources here.
                }
                catch (Throwable e) {
                        throw e;
                }
                finally {
                        System.out.println("Calling finalize method of the Object class");

                        // Calling finalize() of Object class
                        super.finalize();
                }
        }

}

finally

https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

When is it used? for releasing locks on the resources in case of multi-threading, for closing transactions and database connections, etc.

Important: Use a try-with-resources statement instead of a finally block when closing a file or otherwise recovering resources. The following example uses a try-with-resources statement to clean up and close the PrintWriter and FileWriter for the writeList method:

public void writeList() throws IOException {
    try (FileWriter f = new FileWriter("OutFile.txt");
         PrintWriter out = new PrintWriter(f)) {
        for (int i = 0; i < SIZE; i++) {
            out.println("Value at: " + i + " = " + list.get(i));
        }
    }
}

The try-with-resources statement automatically releases system resources when no longer needed. See The try-with-resources Statement. https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html


Links to this note