Java / Java 21 Coding Standards Interview Questions
Why should you avoid finalizers in favor of try-with-resources under Java 21 standards?
Object.finalize() has been deprecated for removal since Java 9 because its execution timing is entirely unpredictable - the garbage collector decides if and when a finalizer runs, so resource cleanup could be delayed indefinitely or, in some cases, never happen before the JVM exits.
// avoid protected void finalize() { connection.close(); } // prefer try (Connection c = dataSource.getConnection()) { // use c } // closed deterministically here, even on exception
Try-with-resources closes a resource deterministically at a precise, visible point in the code - the end of the try block - regardless of whether the block completes normally or throws, which makes cleanup behavior something a reader can verify just by looking at the code, not something dependent on GC internals.
Standards treat any reliance on finalize() for correctness, such as releasing a file handle or a database connection, as a defect: the fix is always to make the resource implement AutoCloseable and manage it with try-with-resources, or, for cleanup tied to object collection specifically, to use the modern Cleaner API instead.
More Related questions...