垃圾收集由静态变量引用的对象 [英] Garbage collection of objects referenced by static variables
问题描述
class StaticTest {
public static SomeClass statVar = new SomeClass();
如果我们访问 StaticTest .statVar
并随机分配一些新对象,然后当所有这些对象都会被垃圾收集?答案:正常的垃圾收集时间。
但是,如果这个 statVar
引用了一些实例变量(对象) ?
不清楚吗?
好了,静态变量的生命期是等到类被卸载的时候。在Web应用程序中,我们正在静态环境中初始化许多事情。如果我们为这个静态上下文提供了一些对象引用,但是我们没有释放它们,那么它如何被垃圾收集呢?
我会很乐意讨论这个。
解决方案静态变量引用的对象将在类卸载时被垃圾回收。所以,静态引用所引用的对象在类被卸载之前不会被GCed(因为在堆中总是有可达的对象引用)。
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.
解决方案 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).
这篇关于垃圾收集由静态变量引用的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!