The object survives after being GCed at least once in its lifetime

Finalize call process: During GC, when the object becomes unreachable (GC Roots), if the object overwrites (overrides) the finalize method and the finalize method has not been executed, it will be put into the F-Queue queue, from a low The priority thread executes the finalize method of the objects in the queue; otherwise, it will be recycled directly. After the finalize method is executed, the GC will again determine whether the object is reachable. If it is not reachable, it will be recycled. Otherwise, the object will be "resurrected".

system.gc() is not executed immediately after you call it, but calculates the time to execute garbage collection according to various algorithms of the virtual machine. In addition, garbage collection will not be executed when the program ends automatically. Second: when the object is recycled, it must be marked twice. The first time is marked. If finalize has not been rewritten, or finalize has been called, then the garbage collection will not execute finalize, otherwise the finalize method will be executed; the second time Mark, if the object cannot successfully save itself in finalize, it will really be recycled

Examples are as follows:

public class FinalizeEscapseGC {

public static FinalizeEscapseGC gcObject = null;

public static FinalizeEscapseGC fe = null;

 

public void isAlive() {

System.out.println("I am still Alive");

}

 

@Override

protected void finalize() throws Throwable {

super.finalize();

System.out.println("finalize method excute");

FinalizeEscapseGC.gcObject = this;

}

 

public static void main(String[] args) throws InterruptedException {

gcObject = new FinalizeEscapseGC();

gcObject = null;

System.gc();//Because the finalize method has been overridden and has not been called, the finalize method will be called at this time

Thread.sleep(500);

if (gcObject != null) {

gcObject.isAlive();

} else {

System.out.println("gcObject is dead");

}

gcObject = null;

System.gc();//Because the finalize method has been called at this time, it will not be called again; the object will be recycled directly

Thread.sleep(500);

if (gcObject != null) {

gcObject.isAlive();

} else {

System.out.println("gcObject is dead");

}

}

}

The result is as follows:

finalize method execute//The finalize method is called at the first gc

I am still Alive//After calling finalize, the object is rescued

gcObject is dead//The second call to gc no longer executes the finalize method and recycles directly

 

Reference link: https://blog.csdn.net/h2604396739/article/details/78125305

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325067448&siteId=291194637