Video in progress

What was the finalize() method meant for, and why shouldn't you use it?

finalize() was a "cleanup" method that was supposed to be called before the GC collected an object. There is no guarantee when it is called, it slows the GC down, and it has been deprecated since Java 9 and marked for removal since Java 18.

📖 Answer

The idea: before an object dies, it would close a file or native resource. In practice this didn't work well:

  • the time of the call is unknown, possibly never (if the application exits);
  • an object with finalize() survives at least two GC cycles, so the memory is freed later;
  • finalizers run on a single separate thread; if it is slow, the queue grows and can lead to OOM;
  • inside finalize() you can "resurrect" the object, a source of confusing bugs;
  • exceptions are silently swallowed.

With JEP 421 (Java 18), finalization was deprecated for removal, and you can test by turning it off with --finalization=disabled.

For resources, use AutoCloseable and try-with-resources. If you want a safety net, use java.lang.ref.Cleaner (Java 9+).

try (var in = Files.newInputStream(path)) {
    // work
} // it is definitely closed here