DEV Community

Buddhika Chathuranga
Buddhika Chathuranga

Posted on

Java finalize() is danger

In every Java object, there is a method called finalize(). You can override this method in any of your classes. The purpose of this method was to implement clean-up codes. When the object is garbage collected by the garbage collector, the garbage collector will invoke this method.

But no one can ensure whether the garbage collector will get a chance to invoke that method. Because we can't force to run the garbage collector even by calling System.GC().

Refer to the following code.

public class Demo{
  private DBConnection dbcon;

  public Demo(DBConnection con){
    this.dbcon = con;


  public static void main(String[] args){
    for(int i = 0; i < 1000000; i++){
       Demo demo = new Demo(
         new DBConnection("credentials")
Enter fullscreen mode Exit fullscreen mode

A million database connections will be opened when we run this code, but the connection closing logic is implemented inside the finalize method. Since no one can ensure that the garbage collector will trigger before the application ends, a million database connections may be wasted.

So it is not recommended to override the finalize method. Especially when you want to implement a critical piece of code inside the finalize method.

Because of this, Java has deprecated the finalize method from version 9. But still, if you want to do this, there are few workarounds that you can take.

1. Register a shutdownhook

You can use shutdownhook to execute things like resource cleanups, closing log files, etc. Shutdownhook will be executed by the JVM before shutting down the JVM. You can register as many as shutdownhooks you want and those will be executed concurrently, and you can't tell what order it will be executed.

2. Using PhamtomReference

A phantom reference is a kind of reference in Java, where the memory can be reclaimed. The phantom reference is one of the strengths or levels of 'non-strong' reference defined in the Java programming language; the others being weak and soft.

This is the same definition from Wikipedia about the phantom reference in Java. I have no much clarity about phantom reference. Maybe I will explain this will in another article.
Until that will help you ;).

Top comments (0)