[英]Java Static Classes lifetime
How is a Java static class garbage collected? 如何收集Java静态类垃圾?
I have a static class, which contains a static object. 我有一个静态类,它包含一个静态对象。 If I set the object to null then it is garbage collected.
如果我将对象设置为null,那么它将被垃圾回收。 I don't understand the lifecycle of a static class.
我不了解静态类的生命周期。 Is it garbage collected when the program closes?
程序关闭时是否收集了垃圾?
Static objects are tied with the class definition and not with the class instance. 静态对象与类定义相关联,而不与类实例相关联。
They come into effect as soon as your class is loaded through the ClassLoader and destroyed only when class is unloaded. 它们一旦通过ClassLoader 加载类就会生效,只有在卸载类时才会销毁它们。
Static classes are always accessible and therefore never garbage collected. 静态类始终可访问,因此永远不会收集垃圾。
Now, if your static class has as it's field and instance of a non-static class and that gets set to null, than that memory will be freed up because that object is no longer referenced. 现在,如果您的静态类具有其非静态类的字段和实例,并且将其设置为null,则该内存将被释放,因为不再引用该对象。
for instance 例如
public static StaticClass
{
public static InstanceClass myInstanceClass;
}
if you set myInstanceClass
to null, then it will be garbage collected. 如果你将
myInstanceClass
设置为null,那么它将被垃圾收集。
- static
class can only be at class level not at package level , we can say static inner classes
or Top level classes
. -
static
类只能在类级别而不是包级别 ,我们可以说static inner classes
或Top level classes
。
- A static
class is then loaded by the class loader. -然后由类加载器加载
static
类。
- Now the static
class will be into the memory till the loader that has loaded it is still running or unless its not unloaded by the loader. -现在
static
类将进入内存,直到加载它的加载器仍在运行或除非加载器没有卸载它。
Think of this way: 想一想:
Every object has a reference to its class. 每个对象都有对其类的引用。
Every class has a reference to its class loader. 每个类都有对其类加载器的引用。
Every class loader has a reference to every class it has ever loaded . 每个类加载器都引用它所加载的每个类 。
It is possible that this whole ball of mess becomes garbage. 这整个混乱的球可能变成垃圾。 This is the basis for app unloading/reloading (in a servlet container).
这是(在servlet容器中)卸载/重新加载应用程序的基础。 However if there's even one object still referenced, the class loader and all its classes cannot be unloaded, therefore it is not an easy task to achieve app unloading.
但是,如果仍然有一个对象仍然被引用,则无法卸载类加载器及其所有类,因此实现应用程序卸载并不是一件容易的事。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.