The finalize Method
Some object-oriented programming languages require a programmer to explicitly
destroy objects when they are no longer needed. In the Java programming
language, a programmer does not need to explicitly destroy objects. The Java
Virtual Machine (JVM) is responsible for reclaiming the memory allocated to
different objects when they go out of scope. This process is known as garbage
collection. There are two main characteristics of the garbage collection process.
When an Object Goes Out of Scope, It Is Believed to Be Garbage
This understanding is not entirely accurate. When an object goes out of scope,
it is marked as eligible for garbage collection, but the process of garbage collection
may not begin immediately. The garbage collection process runs periodically to
reclaim the memory occupied by objects that are out of scope and no longer
referenced. This happens in a recursive manner. But there is no exact specification
as to when the JVM should run the garbage collection process.
When the garbage collection process runs, before an object is garbage collected,
the Java runtime system invokes the object’s finalize() method. Any required
clean up operations to release any system resources such as open files or open
© 2004 by CRC Press LLC
sockets can be implemented as part of the finalize() method. The finalize()
method must be declared as:
protected void finalize() throws Throwable
The Garbage Collection Process Runs as a Low-Level Background
In general, it is not essential that a process running on a daemon thread be
allowed to complete before an application terminates.
From these details of the garbage collection process, it can be seen that even
though the finalize() method can be used to perform. clean-up operations,
it is not a reliable option to free system resources in a timely manner. This is
mainly because the garbage collection process, which invokes the finalize()
method on an object, runs at unpredictable times.
来自 “ ITPUB博客 ” ，链接：http://blog.itpub.net/16792402/viewspace-584294/，如需转载，请注明出处，否则将追究法律责任。