Finalize

This lesson talks about the finalize method of the Object class.

We'll cover the following...
1.

Explain the finalize() method

Show Answer
Q1 / Q4
Press + to interact
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.");
}
}

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.