The main research in this article is an attempt to override the finalize() method in Java, and the specific implementation is as follows.
Test code
package com.alio.gc;/** * Execution result: * */public class FinalizeEscapeGC{ public static FinalizeEscapeGC instance=null; public void isAlive(){ System.out.println("yes,i am still alive"); } @Override protected void finalize() throws Throwable { super.finalize(); System.out.println("finalize method executed"); instance=this; } public static void main(String [] args) throws InterruptedException { instance=new FinalizeEscapeGC(); instance=null; System.gc(); Thread.sleep(1000); instance.isAlive(); //When the finalize method is not rewrite, the instance=nullpointerException will definitely be reported; System.gc(); Thread.sleep(1000); instance.isAlive(); }}Execution results:
finalize method executed
yes,i am still alive
Exception in thread "main" java.lang.NullPointerException
at com.alio.gc.FinalizeEscapeGC.main(FinalizeEscapeGC.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
First execute instance=null; then execute instance.isAlive(); when the finalize method is not rewrite, a nullpointerException will definitely be reported.
However, the actual execution result is a success in escape and a failure. This is because the finalize() method of any object will only be automatically called once by the system. If the object faces the next recycle, its finalize() method will not be executed again
This way of saving the object is extremely uncertain. It is recommended that you do not need to use it and forget the existence of this method.
The above is all about the code covering the finalize() method example code in Java, I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!