Directory:
Effective java--End Method Guardian
Effective Java Chapter 2nd: Creating and Destroying objects. 7th: Avoid using the finalization method. The last example of the "End Method Guardian (finalizer Guardian)" to deepen understanding.
1 /**2 * Chapter 2--end Guardian3 * @ClassName: Parent4 * TODO5 * @authorXingle6 * @date 2015-3-11 pm 3:49:477 */8 Public classParent {9 Ten Public Static voidMain (string[] args) { One dosth (); A System.GC (); - Try { -Thread.Sleep (2000); the}Catch(interruptedexception e) { - e.printstacktrace (); - } - } + - /** + * TODO A * @authorXingle at * @data 2015-3-11 pm 3:51:02 - */ - Private Static voiddosth () { -Child C =NewChild (); - System.out.println (c); - } in - Private FinalObject Guardian =NewObject () { to + @Override - protected voidFinalize () { theSYSTEM.OUT.PRINTLN ("Executing anonymous inner class in parent class--end method Guardian, rewritten finalize ()"); * //in this case, a finalize of the parent override is called to call its own cleanup method when the child class is cleaned $ parentlfinalize ();Panax Notoginseng } - }; the + /** A * TODO the * @authorXingle + * @data 2015-3-11 pm 3:55:10 - */ $ protected voidparentlfinalize () { $SYSTEM.OUT.PRINTLN ("Executing the finalization method of the parent class itself"); - } - } the - classChildextendsParent {Wuyi the @Override - protected voidFinalize () { WuSystem.out.println ("Execute the Subclass Finalize method, note that the subclass here does not call Super.finalize ()"); - //because subclasses (forgetting or other reasons) did not call Super.finalize () About //using the finalization method The Guardian can guarantee that the child class executes Finalize () (without calling Super.finalize ()), and the cleanup method of the parent class still calls $ } -}
Execution Result:
Effective java--End Method Guardian