Cleanup: End processing and garbage collection
Java has garbage collection periods that are responsible for reclaiming memory resources occupied by useless objects. But this is also the case: assuming that your object (not using new) obtains a "special" area of memory, because the garbage collection period only knows to release the memory allocated by new, all of it does not know how to dispose of this "special memory" of the object. To cope with this situation, Java allows you to define a method named Finalize () in the class. It works "assumed" to be like this:
Once the garbage collection period is ready to release the storage space occupied by the object, its finalize () method is called first, and the memory occupied by the object is actually reclaimed when the next garbage collection action occurs. So if you're going to use Finalize (), you can do some important cleanup at the time of the garbage collection.
Example simulations:
Suppose an object is drawn to the screen itself during creation, and if it is not explicitly erased from the screen, it may never be cleaned up. If a erase function is added to finalize (), when "garbage collection" occurs (not guaranteed to happen), the Finalize () method is called, the image is erased, and the next garbage collection is reclaimed.
Perhaps you will find that as long as the program is not on the verge of storage space to run out of the moment, the object occupies the space will not be released. If the program execution finishes and the garbage collector has not freed up storage space for any objects you create, those resources will be returned to the operating system as the program exits. This strategy is appropriate because the garbage collection itself has a cost, and if you don't use it, you don't have to pay for that part of the cost.
Finalize use Example: Verifying the finalization condition
public class Testfinalize {
public static void Main (string[] args) {
Book novel = new book (true);
Novel.checkin ();
Drop the reference. Forget to clean up
New book (true);
Force garbage Collection & Finalization
System.GC ();
}
}
Class book{
Boolean checkOut = false;
Book (Boolean checkOut) {
This.checkout = CheckOut;
}
void CheckIn () {
CheckOut = false;
}
protected void Finalize () {
if (CheckOut) {
System.out.println ("error:checked out");
}
}
}
The role of the Java Recovery Finalize method (programming idea)