I. Basic CONCEPTS
1. The so-called finalization method actually refers to finalize ().
2. Java's garbage collection mechanism is responsible for memory-related cleanup only, and cleanup of other resources (releasing files, releasing the DB connection) requires the programmer to do it manually.
3. Calling System.GC () only recommends that the JVM perform garbage collection (GC), but when it executes and whether it is to be executed by the JVM.
4. The user can call the Finalize method of the object itself, but this call is a normal method call, independent of the object's destruction process.
5. If a class implements a Finalize method, the method is bound to be called when the JVM performs garbage collection.
public class C {public static void main (string[] args) {A A = new A (); a.b = new B (); A = null; System.GC ();}} Class A {B b;public void Finalize () {System.out.println ("method a.finalize at" + System.nanotime ())}} Class B {public void Finalize () {System.out.println ("method b.finalize at" + system.nanotime ());}}
Two. Finalize the execution process
When an object is unreachable, the GC will determine if the object overrides the Finalize method, and if it is not overwritten, it is reclaimed directly, otherwise, if the object has not performed a Finalize method, put it into the f-queue queue, and a low-priority thread executes the Finalize method of the object in that queue. After the Finalize method is executed, the GC will again determine whether the object is reachable or not, and then recycle if it is not reachable. Otherwise the object is "resurrected".
Three. Code examples in JDK
To prevent users from forgetting to close resources, the FileInputStream class in the JDK overrides the Finalize method:
/** * Ensures that the <code>close</code> method of this file input stream was * called when there was No more references to it. * * @exception ioexception If an I/O error occurs. * @see java.io.fileinputstream#close () */ protected void Finalize () throws IOException { if (fd! = NULL) && (fd! = filedescriptor.in)) {/ * If FD is GKFX, the references in FileDescriptor * would E Nsure that finalizer are only called when * safe to do. All references using the FD has * become unreachable. We can call Close () */ close (); } }
Four. When to use Finalize
1. Minimize the use of finalize, preferably by system management, we can define other methods to release non-memory resources.
2. If you must use, then you can refer to the FileInputStream class, in the Finalize check the cost of memory resources are released.
Effective Java (7)-Avoid using the finalization method