阅前声明: http://blog.csdn.net/heimaoxiaozi/archive/2007/01/19/1487884.aspx
/****************** Exercise 12 *****************
* Modify Exercise 11 so that your finalize()
* will always be called.
***********************************************/
public class E12_FinalizeAlwaysCalled {
protected void finalize() {
System.out.println("Finalize called");
}
public static void main(String args[]) {
new E12_FinalizeAlwaysCalled();
System.gc();
}
}
**Calling System.gc( ) will probably cause your finalizer to be called. I say “probably” because the behavior of finalize has been uncertain from one version of the JDK to another. In addition, calling System.gc( ) is just a request, and it doesn’t guarantee that the garbage collector will actually be run.
**Another solution that was put into one version of the JDK, and then deprecated in the next version (just to assure you that they know what they’re doing there at JavaSoft) is to call System.runFinalizersOnExit(). Since this is deprecated, you can’t really use it anymore. Basically, there’s no way to ensure that finalize( ) will be called.