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<>();
Advertisement
Answer
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 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.
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; e.g. when a variable that is in scope is not going to be used again.