Finalize Method in Java

Finalize Method in Java

1
2
3
4
5
@Deprecated(
since = "9"
)
protected void finalize() throws Throwable {
}

In Java, finalize() method is defined in java.lang.Object class, which is called before garbage collection.

When an object is no longer referenced by other objects, it can be seen as garbage. Then JVM would collect it in some time. For example, suppose we have a Lion class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Lion {
String name;

public Lion(String name) {
this.name = name;
}

// We override the finalize method.
@Override
protected void finalize() throws Throwable {
System.out.print(name);
System.out.println("'s finalize method is called.");
}
}

Then we can design a case in which the Lion object Mufasa can be garbage collected:

1
2
3
4
5
6
7
public class Main {
public static void main(String[] args) {
Lion lion = new Lion("Mufasa");
lion = new Lion("Simba");
System.gc();
}
}

Since Mufasa is no longer referenced, it would be garbage collected. Therefore, the output of the above code is:

1
Mufasa's finalize method is called.

Note that explicitly calling System.gc() is a bad practice. Here we just use this method to force the JVM to garbage collect Mufasa.


From the above discussion, we can know that the finalize() method can be implicitly called (by JVM) to reclaim memory resource. Besides, programers can also explicitly call this method to close other resources such as sockets and data streams. For example, we can close these resources in finalize() method:

1
2
3
4
5
6
// psudocode
public void finalize () {
socket.close();
inputstream.close();
outputstream.close();
}

Then we can explicitly call finalize() method in our code:

1
2
3
4
5
6
7
try {
//...
} catch (Exception e){
//...
} finally {
finalize();
}

However, the finalize method is deprecated since Java 9. Instead, we can use try-with-resources statement to close our resources, i.e.,

1
2
3
4
5
6
7
try(
// open resources here
) {
//...
} catch (Exception e) {
//...
}

Resources such as Socket and InputStream all implemented the Closable interface, and the Closable interface extended the Autoclosable interface, so that Java can close these resources automatically for us.