10&11
The conditions for finalize() to be called, (1) The class is not called (set null), (2) System.gc() is called.
Note: Java 1.6 and below can be used, 1.8 cannot.
//: Main.java
/** * Garbage collection * Note: Java environment 1.6 can, 1.8 can't, garbage collection mechanism changed.
*/
class Test { @Override protected void finalize(){ System.out.println("finalize"); // super.finalize(); } } class Main { public static void main(String[] args) { Test t = new Test(); t = null; // 确保finalize()会被调用 System.gc(); } } /** * Output: finalize *///:~
12
When cleaning the object, the finalize() function will be called, and the stored data will be retained, such as T2;
when cleaning the object, it will be pushed and popped from the stack, first in and then clean up, and last in, first clean up.
//: Main.java
/** * Garbage collection * Note: Java environment 1.6 can, 1.8 can't, garbage collection mechanism changed.
*/
class Tank { boolean isFull = false; String name; Tank(String name) { this.name = name; } void setEmpty() { isFull = false; } void setFull() { isFull = true; } @Override protected void finalize(){ if (!isFull) { System.out.println(name + ": 清理"); } // super.finalize(); } } class Main { public static void main(String[] args) { Tank t1 = new Tank("T1"); Tank t2 = new Tank("T2"); Tank t3 = new Tank("T3"); t1.setFull(); t2.setEmpty(); t1 = null; t2 = null; t3 = null; System.gc(); } }
/** * Output: T3: 清理 T2: 清理 *///:~