3
votes
class StaticTest{

public static SomeClass statVar = new SomeClass();

}

After this if we access StaticTest.statVar and assign some new objects at random times, then when all these objects will get garbage collected? Answer: In normal garbage collection time.

But what if this statVar has references to some instance variables(objects)?

Not clear?

Ok, static variables life time is until the class unloaded. In web applications we are initializing many things in static context. Incase if we are providing some object references to this static context but we are not releasing them, then how it gets garbage collected?

I would be very happy to discuss on this.

3
Your question is very unclear at the moment... it would really help if you'd provide a full, concrete example with a specific questoin. - Jon Skeet
What do you mean by "not releasing them"? If something references a value, it won't be GCed. If nothing references it, it may be. - Dave Newton
Thanks for all your answers. I have some design issue. For each request there are objects getting created. Context is same for all requests. If request objects are given reference by context(Static here) variables, so these objects never get garbage collected until server restart? correct? - Ratnakar.class

3 Answers

5
votes

Objects referenced by static variable will be garbage collected at the time of class unloading. So, what ever the objects being referenced by the static reference won't be GCed until class-unloaded (Because there is always a reachable reference to object in heap).

0
votes

Think about the Objects in memory, not the variables. statVar is a reference to some object in memory. If you retain a reference to the same Object somewhere else, then the Object will not be GC'd until that reference is released. It doesn't matter if the class is unloaded and statVar goes away, because that's just another reference to an Object that still has references living. So, it will not be cleaned in that case.

0
votes

static object references are typically considered GC roots and whatever they point to (and whatever is tied up by those objects) will be considered live. If you want the object they refer to to be subject of a garbage collection you will need to clear the reference to them (and all other references as well of course).

If your class is no longer referenced and your JVM is set to collect unused classes, thinksteep's answer apply. I wouldn't hold my breath waiting for that moment.

As long as you keep the data referenced the answer is simply that they will not be cleared. That's the most fundamental part of the protocol when you have a GC.

As a side note, I rarely think it is a good idea to keep things in a static context in web-apps unless it is a singleton object or something which is shared by all users of that web-app. In that case, why would you want it to be cleaned up as long as your app server is running? It doesn't make sense.