简体   繁体   English

static 列表中的对象是否符合垃圾回收条件?

[英]Are objects inside a static list eligible for garbage collection?

I know that static variables are not eligible for garbage collection for as long as the class is loaded but i was wondering if that is the same case for it's object contents.我知道只要加载了 class,static 变量就没有资格进行垃圾回收,但我想知道 object 的内容是否也是如此。 I have this static List which contains a class object references.我有这个 static 列表,其中包含 class object 参考。 Are "someObject" eligible for garbage collection if no one's referencing them?如果没有人引用“someObject”,是否有资格进行垃圾回收?

private static List<SomeObject> mylist = new ArrayList<>();

I was wondering if that is the same case for it's object contents.我想知道它的 object 内容是否也是这种情况。

Yes, it is the same for the object's contents.是的,对象的内容是一样的。 And their contents.以及它们的内容。 And their contents... etcetera.以及它们的内容……等等。

An object is reachable if some part of your application could try to access it at some point in the future. object 如果您的应用程序的某些部分可以在将来的某个时间点尝试访问它,则它是可访问的。

Or another way to put it (in practice 1 ) is that an object is reachable if there is a path to it via a chain of references, starting at a GC root.或者另一种表达方式(在实践中1 )是 object 是可到达的,如果通过引用链从 GC 根开始到它有一条路径 Static variables are GC roots, as are thread stacks. Static 变量是 GC 根,线程栈也是。


Are "someObject" eligible for garbage collection if no one's referencing them?如果没有人引用“someObject”,是否有资格进行垃圾回收?

If an object is in a list, it is referenced by the list.如果 object 在列表中,则它被列表引用。 If the list is reachable, then so are its contents.如果列表是可达的,那么它的内容也是可达的。


1 - In theory, a compiler could determine that while a path exists to an object, in reality the path is never going to be followed. 1 - 理论上,编译可以确定虽然存在指向 object 的路径,但实际上永远不会遵循该路径。 However, that requires some difficult / expensive analysis by the compiler.但是,这需要编译器进行一些困难/昂贵的分析。 So this is an optimization approach that typically doesn't get tried, except in limited cases;所以这是一种通常不会尝试的优化方法,除非在有限的情况下; eg when a variable that is in scope is not going to be used again.例如,当不再使用 scope 中的变量时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM