5.12. The finalize() Method
You have the option of including a method finalize() in a class definition. This method is called automatically by Java before an object is finally destroyed and the space it occupies in memory is released. In practice this may be some time after the object is inaccessible in your program. When an object goes out of scope, it is dead as far as your program is concerned, but the Java Virtual Machine may not get around to disposing of the remains until later. When it does, it calls the finalize() method for the object. The form of the finalize() method is:
protected void finalize() {
// Your clean-up code...
}
This method is useful if your class objects use resources that require some special action when they are destroyed. Typically these are resources that are not within the Java environment and not guaranteed to be released by the object itself. These could be such things as graphics resources, fonts or other drawing-related resources that are supplied by the host operating system, or external files on the hard disk. Leaving these around after an object is destroyed wastes system resources and, in some circumstances (with graphics resources under some older versions of Windows, for example) if you waste enough of them, your program, and possibly other programs the system is supporting, may stop working. For most classes this is not necessary, but if an object opened a disk file for example, but did not guarantee its closure, you would want to make ...
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.
Read now
Unlock full access