Cleanup总结---Thinking in java 英文版部分小结

来源:互联网 发布:php支付宝服务端demo 编辑:程序博客网 时间:2024/05/22 19:20

Initialization&Cleanup

Cleanup: finalization and garbage collection

    1.Your objects might not get garbage collected.

    2.Garbage collection is not destruction.

    3.Garbage collection is only about memory.

 

The garbage collector only knows how to release memory allocated with new, so it won’t know how to release the object’s “special” memory. 

 

finalize( ): It turns out that the need for finalize( ) is limited to special case in which your object can allocate storage in some way other than creating an object.

 

    This can happen primarily through native methods (固有方法), which a way to call non-java code from java (do something C-like).

   Egcall free( ) (a C and C++ function) in a native method inside your finalize( ).

        If any potions of the object are not properly cleaned up , than you have a bug in your program that can be very difficult to find. finalize( ) can be use to eventually discover this condition, even if it isn’t aways called.   

Eg:TerminationCondition.java

//initialization/TerminationCondition.java//Useing finalize() to detect an object an object that//hasn't been properly cleaned upclass Book {boolean checkedOut = false;Book(boolean checkOut) {checkedOut = checkOut;}void checkIn() {checkedOut = false;}protected void finalize() {if (checkedOut) System.out.println("Error: checked out ");//output tag//you can also do this ://try {//super.finalize();//System.out.println("Error: checked out too");//output tag//}  catch (Throwable e) {////do nothing//}}}public class TerminationCondition {public static void main (String[] args) {Book novel = new Book(true);novel.checkIn();new Book(true);System.gc();//force finalization}}


原创粉丝点击