Clear java-4.5 objects from the ground up (finalize ())
In this section, we will briefly discuss how to clean up objects.
Note: The Destructor is provided in c ++ to clear objects. However, in java, objects are recycled by the garbage collector. The recycle object is not necessarily destructed, because it is recycled only when the memory of the recycler exceeds a certain limit. Therefore, it is possible that the object is only recycled, however, only when the program is closed will the structure be destructed, because the recycler has not reached the limit.
In JAVA, finalize () is generally used to indicate object recycling.
package com.ray.ch01;public class Test {public static void main(String[] args) {try {new Test().finalize();} catch (Throwable e) {e.printStackTrace();}}}
When the object calls finalize (), it will be recycled in the next garbage collection.
Note that the collection of objects is only related to memory.
However, we need to use garbage collection with caution in the code, because it is unpredictable and dangerous.
We usually use the finalize () function as a gc condition detection.
package com.ray.ch01;public class Test {public static void main(String[] args) {Book book = new Book(true);book.checkIn();new Book(true);System.gc();}}class Book {private boolean checkOut = false;public Book(boolean checkOut) {this.checkOut = checkOut;}public void checkIn() {this.checkOut = false;}@Overrideprotected void finalize() throws Throwable {if (checkOut) {System.out.println(error);//super.finalize();}}}
Output:
Error
The above code can be correctly displayed only under debug conditions.
Summary: This chapter mainly discusses some considerations for object cleanup. But in fact, object cleanup is a very big topic. We can only expand it more deeply.