静态列表中的对象是否有资格获得垃圾收集?
我知道,只要加载了该类,静态变量就不符合垃圾收集的条件,但是我想知道这是否是对象内容的情况相同的情况。我有此静态列表,其中包含类对象引用。如果没有人引用垃圾,是否有资格获得垃圾收集?
private static List<SomeObject> mylist = new ArrayList<>();
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. I have this static List which contains a class object references. Are "someObject" eligible for garbage collection if no one's referencing them?
private static List<SomeObject> mylist = new ArrayList<>();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,对象的内容是相同的。和他们的内容。和他们的内容...等。
如果您的应用程序的某些部分可以尝试在将来的某个时候访问它,则可以到达对象。
或另一种将其放置的方法(在实践中 1 )是,如果从GC根开始,则可以通过参考链来达到对象。静态变量是GC根,线程堆栈也是如此。
如果对象在列表中,则列表引用。如果列表是可访问的,那么它的内容也是如此。
1-从理论上讲,编译器可以确定 在对象存在路径时,实际上永远不会遵循该路径。但是,这需要编译器进行一些困难 /昂贵的分析。因此,这是一种通常不会尝试的优化方法,除非有限的情况。例如,当不再使用范围中的变量时。
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.
Or another way to put it (in practice1) is that an object is reachable if there is a path to it via a chain of references, starting at a GC root. Static variables are GC roots, as are thread stacks.
If an object is in a list, it is referenced by the list. 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. 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; e.g. when a variable that is in scope is not going to be used again.