Ratnakar.class
Ratnakar.class

Reputation: 320

Garbage collection of objects referenced by static variables

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.

Upvotes: 5

Views: 5389

Answers (3)

kosa
kosa

Reputation: 66677

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

Upvotes: 7

Fredrik
Fredrik

Reputation: 5849

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.

Upvotes: 0

Carl
Carl

Reputation: 915

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.

Upvotes: 0

Related Questions