Difficulty: Medium
Correct Answer: It may be called once by the garbage collector on an object before the object memory is reclaimed, in order to release non Java resources.
Explanation:
Introduction / Context:
The finalize() method in Java is a special method that historically allowed an object to perform cleanup before the JVM reclaimed its memory. Although modern best practice discourages heavy reliance on finalization, understanding when finalize() may run and why it was introduced is still important for interviews and legacy code maintenance.
Given Data / Assumptions:
Concept / Approach:
When an object becomes eligible for garbage collection, the JVM may choose to invoke its finalize() method once, before reclaiming the memory. The main idea is to let the object release non Java resources such as file handles, native memory, or database connections that are not automatically cleaned up by the garbage collector. However, there is no guarantee about timing, order, or even whether finalize() runs at all, so production code should rely on explicit cleanup patterns instead.
Step-by-Step Solution:
Verification / Alternative check:
Developers can override finalize(), add logging, and then run code that discards references to the object. By monitoring logs and forcing memory pressure, they may observe that finalize() runs, but often not immediately. This experiment illustrates the lack of strict guarantees about the timing of finalization.
Why Other Options Are Wrong:
Common Pitfalls:
A frequent mistake is to rely on finalize() for releasing critical resources or for business logic. Because finalization is unpredictable, code should instead use try finally blocks, try with resources, or explicit close methods. Another pitfall is assuming that overriding finalize() improves performance, when it usually makes garbage collection slower and more complex.
Final Answer:
The correct choice is It may be called once by the garbage collector on an object before the object memory is reclaimed, in order to release non Java resources. because this captures both the timing and the intended purpose of finalization in Java.
Discussion & Comments