Junior — Middle
What is the role of the finalize() method in the Object class and what is its purpose?
sobes.tech AI
Answer from AI
The finalize() method in the Object class is intended to perform cleanup before the object is garbage collected. It is a kind of destructor in Java, which is called automatically by the system.
The purpose of finalize() is to release resources that are not managed by the JVM, such as closing files, network connections, etc.
However, using finalize() is not recommended because:
- Calling
finalize()is not guaranteed and may be delayed. - It negatively impacts performance.
- There are more modern and reliable ways to manage resources, such as try-with-resources and the
AutoCloseableinterface.
Example of overriding:
@Override
protected void finalize() throws Throwable {
try {
// resource cleanup
} finally {
super.finalize();
}
}
In modern applications, it is better to avoid finalize() and use other resource management mechanisms.