Java 虚拟机枚举 GC Roots 解析

JVM 堆内存模型镇楼。html

读《深刻理解Java 虚拟机》第三章GC算法,关于 GC Roots 枚举的段落没说透彻,理解上遇到困惑。所以对这点进行扩展并记录,发现国内各类博客写来写去都是几乎相同的分析,仍是没厘清困惑:GC Roots 到底是如何枚举的,其中用到的 OopMap 是一个什么样的数据结构?java

Recap:三大GC算法

一、标记清除算法(Mark-Sweep)算法

二、复制算法(Copying)bash

三、标记整理算法(Mark-Compact)数据结构

三种算法都用到了可达性分析方法来对对象进行标记清除。app

可达性分析方法分三大步骤:

Step One: Enumerations of Roots.ide

找到瓜藤的根。性能

Step Two: Marking all object references starting from the roots.ui

从根节点出发,顺藤摸瓜,每次摸到一个瓜,就打上标记--这瓜还没熟,别摘!google

Step Three: Sweeping all the unmarked objects.

顺理成章,那些没被标记上的瓜天然就是熟了的瓜,通通收走拿去吃掉。

以上过程对应的伪代码以下:

Void GC() {

    HaltAllProcessing();
    
    ObjectCollection roots = GetRoots();
    for(int i=0; i<roots.Count(); ++i) {
        Mark(roots[i]);
    }
    
    Sweep();
    
}
复制代码

疑问点:什么是根节点 GC Roots?

For your application code to reach an object, there should be a root object which is connected to your object as well as capable of accessing from outside the heap. Such root objects that are accessible from outside the Heap are called Garbage Colllection (GC) roots. There are several types of GC roots such as Local variables, Active Java threads, Static variables, JNI References etc. (Just take the ideology here, if you do a quick google search, you may find many conflicting classifications of GC roots)

对于一个 Java 程序而言,对象都位于堆内存块中,存活的那些对象都被根节点引用着,即根节点 GC Roots 是一些引用类型,天然不在堆里,那它们位于哪呢?它们能放在哪呢?

答案是放在栈里,包括:

Local variables 本地变量

Static variables 静态变量

JNI References JNI引用等

GC Roots are objects that are themselves referenced by the JVM and thus keep every other object from being garbage-collected.

如何快速枚举 GC Roots?

一、笨方法:遍历栈里全部的变量,逐一进行类型判断,若是是 Reference 类型,则属于 GC Roots。

二、高效方法:从外部记录下栈里那些 Reference 类型变量的类型信息,存成一个映射表 -- 这就是 OopMap 的由来

“在解释执行时/JIT时,记录下栈上某个数据对应的数据类型,好比地址1上的”12344“值是一个堆上地址引用,数据类型为com.aaaa.aaa.AAA)

如今三种主流的高性能JVM实现,HotSpot、JRockit和J9都是这样作的。其中,HotSpot把这样的数据结构叫作 OopMap,JRockit里叫作livemap,J9里叫作GC map。”

GC 时,直接根据这个 OopMap 就能够快速实现根节点枚举了。

参考连接:

Understanding Java Garbage Collection

JVM中的OopMap

相关文章
相关标签/搜索