The reading and coding of the idea of Java programming one hour a day starting today is actually copying the code from the book.
- 5.5 Cleanup: End Processing and garbage collection
Initialization and cleanup work are equally important, but cleanup is often forgotten, but after using objects, it is not safe to abandon objects. Java has its own garbage collector responsible for reclaiming memory resources that are occupied by useless objects. But there are also special cases: Suppose that your memory area is not obtained with new, which is not available in the garbage collector, so Java allows you to define a method named Finalize () in the class .
Working principle:
Once the garbage collector 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. (unlike destructors in C + +, new is created in C + +, delete is destroyed, and if you forget, a memory leak occurs, and objects in Java are not all garbage collected) the following are three points:
- Object may not be garbage collected
- Garbage collection does not equal destruction
- Garbage collection is only related to memory
Although there is garbage collection in Java, it does not replace the function of destructors in C + + completely .
Example:
1 //: Initialization/terminationcondition.java2 //Using Finalize () to detect a object that3 //hasn ' t been properly cleaned up4 classbook{5 BooleanCheckedout =false;6Book (BooleanCheckOut) {7Checkedout =CheckOut;8 }9 voidcheckIn () {TenCheckedout =false; One } A protected voidFinalize () { - if(checkedout) -System.out.print ("error:checked out"); the //Normally, you'll also do this: - //super.finalize ();//Call the Base-class version - } - } + - Public classrock{ + Public Static voidMain (String []args) { ABook Novle =NewBook (true); at Novle.checkin (); - NewBook (true); - System.GC (); - - } -}
Output
Error:checked out
Note: System.GC () is used to force the finalization action
*
Java Programming Ideas The fifth chapter----initialization and Cleanup (1)