Does JVM/GC call `finalize()` on program/thread exit?

No, Java does not guarantee that on program exit the GC will trigger. If you want an operation to peform on exit use Runtime.addShutdownHook method. Read this Sun article on what the SPEC says.

The specification for the Java platform makes very few promises about
how garbage collection actually works. Here is what the Java Virtual
Machine Specification (JVMS) has to say about memory management.

The heap is created on virtual machine start-up. Heap storage for
objects is reclaimed by an automatic storage management system (known
as a garbage collector); objects are never explicitly deallocated. The
Java virtual machine assumes no particular type of automatic storage
management system, and the storage management technique may be chosen
according to the implementor’s system requirements.1 While it can seem
confusing, the fact that the garbage collection model is not rigidly
defined is actually important and useful-a rigidly defined garbage
collection model might be impossible to implement on all platforms.
Similarly, it might preclude useful optimizations and hurt the
performance of the platform in the long term.

Although there is no one place that contains a full definition of
required garbage collector behavior, much of the GC model is
implicitly specified through a number of sections in the Java Language
Specification and JVMS. While there are no guarantees about the exact
process followed, all compliant virtual machines share the basic
object lifecycle described in this chapter.

Leave a Comment