首页 > 解决方案 > Does all values which a static object went through take up space in memory while class is loaded?

问题描述

I know that static variables are stored in a specific place in memory. Whenever you declare an object as static, that object will never be recycled by gc as long as that class is loaded by the classloader .. so far so good.

But imagine that the variable that I defined as static has an internally non-static list, so even though the object itself will never be recycled, will that list be recycled normally? And even if I assign a new instance to a static object, will the old value not be recycled? Would all the values ​​that this object went through take up space in memory?

标签: javamemorystaticgarbage-collectionjvm

解决方案


垃圾收集器从 开始扫描gc roots,其中一个根是static字段。

因此 aGC将遍历从该根“开始”的所有条目,例如:

   SomeStaticInstance
          |
         \ /
     NonStaticList

如果NonStaticList是可达marking的(gc 阶段的阶段负责这个),它被认为是活着的,因此不符合GC. 如果无法访问,则有资格收集。请注意,如果它不可访问,mark phase甚至不会遍历任何可能具有来自 NonStaticList的引用:

 NonStaticList
       |
      \ /
    RefHere

所以RefHere不会被扫描。如果它有来自其他地方的引用,而不是来自NonStaticList.


推荐阅读