Java Core & JVM (50 Qs)•Part 2: Advanced Concurrency, Memory & Modern Java Architecture (11 - 24)
What are final, finally, and finalize, and why was finalize() deprecated?
senior LevelSystem Design
In Simple Words:
final: Keyword indicating immutability. Afinalvariable cannot be reassigned; afinalmethod cannot be overridden; afinalclass cannot be subclassed.finally: Block following atry-catchblock that is guaranteed to execute regardless of whether an exception is thrown or caught (except inSystem.exit()).finalize(): Deprecated method onjava.lang.Objectoriginally intended to clean up resources before an object was garbage-collected.
Why finalize() was Deprecated in Java 9 & Removed:
- Unpredictable Execution: The JVM gives zero guarantee on when or if
finalize()will run. - Performance Degradation: Finalizable objects survive multiple GC generations, bloating young generation promotion and causing massive GC pauses.
- Object Resurrection: A poorly written finalizer can reassign
thisto a static variable, resurrecting an already dead object! - Modern Replacement: Always use
AutoCloseablewithtry-with-resourcesorjava.lang.ref.Cleaner.