Garbage collection of objects referenced by static variables

。_饼干妹妹 提交于 2019-12-22 10:20:03

问题


class StaticTest{

public static SomeClass statVar = new SomeClass();

}

After this if we access StaticTest.statVar and assign some new objects at random times, then when all these objects will get garbage collected? Answer: In normal garbage collection time.

But what if this statVar has references to some instance variables(objects)?

Not clear?

Ok, static variables life time is until the class unloaded. In web applications we are initializing many things in static context. Incase if we are providing some object references to this static context but we are not releasing them, then how it gets garbage collected?

I would be very happy to discuss on this.


回答1:


Objects referenced by static variable will be garbage collected at the time of class unloading. So, what ever the objects being referenced by the static reference won't be GCed until class-unloaded (Because there is always a reachable reference to object in heap).




回答2:


Think about the Objects in memory, not the variables. statVar is a reference to some object in memory. If you retain a reference to the same Object somewhere else, then the Object will not be GC'd until that reference is released. It doesn't matter if the class is unloaded and statVar goes away, because that's just another reference to an Object that still has references living. So, it will not be cleaned in that case.




回答3:


static object references are typically considered GC roots and whatever they point to (and whatever is tied up by those objects) will be considered live. If you want the object they refer to to be subject of a garbage collection you will need to clear the reference to them (and all other references as well of course).

If your class is no longer referenced and your JVM is set to collect unused classes, thinksteep's answer apply. I wouldn't hold my breath waiting for that moment.

As long as you keep the data referenced the answer is simply that they will not be cleared. That's the most fundamental part of the protocol when you have a GC.

As a side note, I rarely think it is a good idea to keep things in a static context in web-apps unless it is a singleton object or something which is shared by all users of that web-app. In that case, why would you want it to be cleaned up as long as your app server is running? It doesn't make sense.



来源:https://stackoverflow.com/questions/11908342/garbage-collection-of-objects-referenced-by-static-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!