Search⌘ K
AI Features

Finalize

Explore the deprecation of the finalize() method in Java introduced with JDK 9. Understand why this method should be avoided and how it impacts object lifecycle management and future Java releases.

We'll cover the following...
1.

Explain the finalize() method

Show Answer
1 / 4
Java
import java.util.HashSet;
class Demonstration {
static HashSet<UsefulObjectClass> immortals = new HashSet<>();
public static void main( String args[] ) throws InterruptedException {
UsefulObjectClass obj = new UsefulObjectClass(immortals);
obj.printName();
obj = null;
Runtime.getRuntime().gc();
// Sleep the main thread so that the garbage collector thread performs finalization
Thread.sleep(1000);
if (immortals.size() == 1) {
System.out.println("Useful object saved from garbage collection.");
}
System.out.println("exiting");
}
}
class UsefulObjectClass {
HashSet<UsefulObjectClass> immortals;
public UsefulObjectClass(HashSet<UsefulObjectClass> immortals) {
this.immortals = immortals;
}
@Override
public void finalize() {
System.out.println("I am being finalized.");
immortals.add(this);
}
public void printName() {
System.out.println("Hi, I am a useful object.");
}
}
1.

How many times does JVM invoke the finalize() method on an object?

Show Answer
Did you find this helpful?

With the release of JDK 9 finalize() has been deprecated. Deprecation does not necessarily mean removal or future removal. It is an indication used to note that the annotated element should (if possible) be avoided and may potentially be removed in future releases of the Java platform.