Finalize Method in Java
Finalize Method in Java
1 | ( |
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 | public class Lion { |
Then we can design a case in which the Lion object Mufasa
can be garbage collected:
1 | public class Main { |
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 | // psudocode |
Then we can explicitly call finalize()
method in our code:
1 | try { |
However, the finalize method is deprecated
since Java 9. Instead, we can use try-with-resources statement to close our resources, i.e.,
1 | try( |
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.