简体   繁体   中英

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. 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<>();

I was wondering if that is the same case for it's object contents.

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 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. Static variables are GC roots, as are thread stacks.


Are "someObject" eligible for garbage collection if no one's referencing them?

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; eg when a variable that is in scope is not going to be used again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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