This content originally appeared on DEV Community and was authored by rahul khattri
TL;DR: Never!
The finalize() method in Java was originally designed to let developers clean up resources before an object is reclaimed by the Garbage Collector.
But hereβs the catch:
It is not guaranteed to be called.
Its execution is totally unpredictable.
Relying on it means your resources (like file handles, DB connections, sockets) may never actually close.
Instead of finalize(), the modern and reliable approach is:
Try-with-resources (introduced in Java 7):
try (FileInputStream fis = new FileInputStream("data.txt")) {
// use the resource
} catch (IOException e) {
e.printStackTrace();
}
This ensures that resources are automatically closed once the block is done β no surprises, no waiting for the GC.
This content originally appeared on DEV Community and was authored by rahul khattri