Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

The Finalize Method

Problem

You want to have some action taken when your objects are removed from service.

Solution

Use finalize( ) but don’t trust it; or, write your own end-of-life method.

Discussion

Developers coming from a C++ background tend to form a mental map that has a line of equivalency drawn from C++ destructors to Java finalizers. In C++, destructors are called automatically when you delete an object. Java, though, has no such operator as delete; objects are freed automatically by a part of the Java runtime called the garbage collector, or GC. GC runs as a background thread in Java processes and looks around every so often to see if there are any objects that are no longer referred to by any reference variable. When it runs, as it frees objects, it calls their finalize( ) methods.

For example, what if you (or some code you called) invoke System.exit( ) ? In this case the entire JVM will cease to exists (assuming there isn’t an applet-style security manager to deny it permission to do so) and the finalizer is never run. Similarly, a “memory leak” or mistakenly held reference to your object will also prevent finalizers from running.

Can’t you just ensure that all finalizers get run simply by calling System.runFinalizersOnExit(true) ? Not really! This method is deprecated (see Section 1.10); the documentation notes:

This method is inherently unsafe. It may result in finalizers being called on live objects while other threads are concurrently manipulating those objects, resulting ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata