In the reachability algorithm, the search starts from the GC Root object.
What is theGC Root
object
Objects referenced in the VM stack
public class Rumenz{ public static void main(String[] args) { Rumenz a = new Rumenz(); a = null; }}Copy the code
A is the local variable in the stack frame, and a is GC Root. Since a=null,a is disconnected from the new Rumenz() object, so the object is reclaimed.
An object referenced by a static member of a method area class
public class Rumenz{ public static Rumenz=r; public static void main(String[] args){ Rumenz a=new Rumenz(); a.r=new Rumenz(); a=null; }}Copy the code
The local variable a=null in the stack frame will be collected because a is disconnected from the GC Root object (object A). Since the Rumenz member variable r is assigned a reference to a variable, and the r member variable is static, r is a GC Root object, so objects to which r refers are not reclaimed.
The object referenced by the method area constant
public class Rumenz{ public static final Rumenz r=new Rumenz(); public static void main(String[] args){ Rumenz a=new Rumenz(); a=null; }}Copy the code
Objects referenced by constant R are not reclaimed by objects referenced by a.
Objects referenced by JNI in the local method stack
JNIEXPORT void JNICALL Java_com_pecuyu_jnirefdemo_MainActivity_newStringNative(JNIEnv *env, jobject instance, jstring jmsg) { ... // Cache String class jclass jc = (*env)->FindClass(env, STRING_PATH); }Copy the code
A native method is an interface that Java uses to call non-Java code that is not implemented in Java, but might be implemented in other languages like C or Python. Java uses JNI to call native methods. Native methods are stored as libraries (DLL files on WINDOWS platforms, SO files on UNIX machines). By calling the internal methods of the local library file, JAVA can implement close contact with the local machine, calling the system level interface methods,
When a Java method is called, the virtual machine creates a stack frame and pushes it into the Java stack. When it calls a local method, the virtual machine leaves the Java stack unchanged and does not push new jacks in the Java stack. The virtual machine simply dynamically connects and calls the specified local method directly.