Sunday, December 5, 2021

[Java] Garbage collection

JVM memory

Heap、Method Area 都是在虚拟机启动时创建,虚拟机退出时释放。

两种GC方法:










what are GC roots ?
    可以作为GC Root 引用点的是:
  1. JavaStack中的引用的对象。
  2. 方法区中静态引用指向的对象。
  3. 方法区中常量引用指向的对象。
  4. Native方法中JNI引用的对象。


线程共享的 Heap 区、Method Area 则是 GC 关注的重点对象

mark-sweep 标记清除法
mark-copy 标记复制

mark-compact 标记压缩



generation-collect 分代收集算法

eden full --> minor GC(young GC) : mark-copy(eden, S0)
eden full again -> minor GC : mark-copy(S0, S1); mark-copy(eden, S1);

after this S0 is empty, so we swap usage of S0 and S1 for next round :

eden full --> minor GC(young GC) : mark-copy(eden, S1)
eden full again -> minor GC : mark-copy(S1, S0); mark-copy(eden, S0);

after N minor GC, there are objects moved between S1 and S2 N times : promotion to old generation.

old gen full --> major GC (full GC) mark-compact(oldGen)

heap区又分:Eden Space(伊甸园)、Survivor Space(幸存者区)、Tenured Gen(老年代-养老区)。
非heap区又分:Code Cache(代码缓存区)、Perm Gen(永久代)、Jvm Stack(java虚拟机栈)、Local Method Statck(本地方法栈)。

对于Java8,HotSpots取消了永久代,那么是不是就没有方法区了呢?当然不是,方法区只是一个规范,只不过它的实现变了。

在Java8中,元空间(Metaspace)登上舞台,方法区存在于元空间(Metaspace)。同时,元空间不再与堆连续,而且是存在于本地内存(Native memory)

本地内存(Native memory),也称为C-Heap,是供JVM自身进程使用的。当Java Heap空间不足时会触发GC,但Native memory空间不够却不会触发GC。

Ref:

https://www.infoq.cn/article/3wyretkqrhivtw4frmr3


How to implement a swap_sweep?

C++ style: 

template<class T>
class Resource
{
    T * t;
    std::set<Resource*> references;    
}

void visit(std::set<Resource> & visited, const Resource & current)
{
        visited.insert(current);
       for(auto r : current.references)
       {
            if(r)
                if(*r not in visited)
                {
                    visit(visited, *r)
                }        
        }
}

template<class T>
void mark_sweep(std::set<Resource> heap, std::set<Resource> rootReferences)
{
    //mark
    std::set<Resource>  visited;
    for(const aut & r : rootReferences)
    {
        auto it = visited.find(r);
        if(it!=visited.end())
        {
                visit(visited, heap);
        }
    }


    for(auto r : heap)
    {
        if(r not in visited)
        {
            destroy r
        }
    }
}




No comments:

Post a Comment