Skip to main content

The finalize() Method

When the Garbage Collector identifies an object as unreachable and decides to destroy it, it doesn't just instantly delete the memory.

Just before the object is completely removed from memory, the Garbage Collector Thread calls a special method on the object called finalize().


What is the purpose of finalize()?

The finalize() method belongs to the java.lang.Object class, which means every single class in Java inherits it.

Its original purpose was to give the object one "last chance" to perform cleanup operations (like closing open files, releasing network connections, or closing database connections) before it is destroyed.

If you want to define custom cleanup behavior for your class, you must override the finalize() method.

Example

class Connection {

private String dbName;

public Connection(String dbName) {
this.dbName = dbName;
System.out.println("Connection established to " + dbName);
}

// Overriding finalize to ensure the connection is closed
@Override
protected void finalize() throws Throwable {
System.out.println(
"Closing database connection to " + dbName + " right before destruction."
);
}
}

public class LabFinalize1 {

public static void main(String[] args) {
// Create an object and immediately discard the reference
new Connection("CustomerDB");

// Request GC so we can see the finalize method execute
System.gc();

System.out.println("Main method completed.");
}
}

Possible Output:

Connection established to CustomerDB
Main method completed.
Closing database connection to CustomerDB right before destruction.

(Note: Because System.gc() is just a request, the order of the last two lines is not guaranteed. The GC thread runs independently of the main thread).


Why you should NOT use finalize()

[!WARNING] The finalize() method was officially DEPRECATED in Java 9. You should avoid using it in modern Java applications.

Why was it deprecated?

  1. Unpredictability: Because you cannot guarantee when or even if the Garbage Collector will run, you cannot guarantee when finalize() will be executed. If you rely on finalize() to close an important file, that file might stay locked for hours!
  2. Performance Impact: Objects with a finalize() method take much longer for the Garbage Collector to process, slowing down the entire application.
  3. Resurrection: A badly written finalize() method could accidentally reassign the object to a static variable, bringing the object "back to life" and ruining the GC process.

The Modern Solution: If you need to ensure resources are cleaned up, use the try-with-resources statement (introduced in Java 7) which guarantees resources are closed immediately after the try block finishes execution.