gcRoot and reference types in Java

Seeing an old question, how does Java decide which objects to recycle?

Answer: An object that is unreachable from the gcRoot root search and has not been resurrected after being marked and cleaned once will be identified as a garbage object for cleaning. Note that in Java there is no object scope, only object reference scope. Java garbage collection does not use a reference counting algorithm, because it does not solve the problem of circular references. The Java garbage algorithm actually marks those objects that are referenced and used, and the others that are not marked are useless and can be recycled, instead of directly finding out which objects are useless.

So, which objects can be used as gcRoot?

It is actually a set of root references, mainly including the local variable table in the virtual machine stack (actually all the parameters local variables of the method being called, etc.), the static attribute reference of the class, the constant object reference, and the object reference in the local method stack. . In fact, Java garbage collection is mainly for heap memory, and these references come from other parts of the JVM runtime data area: virtual machine stack, local method area, method area.

What are the types of reference types in Java and what are their uses?

The most commonly used are strong references. As long as this reference exists, the object it points to will not be cleaned up during garbage collection. The second is soft references. Only when there is insufficient memory space for garbage collection, the objects pointed to by such references will be reclaimed, and they are mostly used in cache objects. Then there are weak references, which are collected whenever a garbage collection occurs. Finally, there are phantom references, which are the weakest kind of reference relationship.

Guess you like

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