When do strings and static fields get reclaimed by the garbage collector?
I'm asking this because I know static
s开发者_JAVA百科 in ASP.NET are always live.
The garbage collector only collects objects that are not accessible. An object referenced by a static field is accessible as soon as its class is loaded, so it will obviously not get collected (unless of course the field is set to refer to something else, causing the original object to become potentially eligible for collection).
As for strings, it depends. Literal strings are interned and therefore always accessible. Otherwise, same rules apply as for any object.
Strings are objects and will be collected when un-referenced.
static fields usually keep a permanent reference to an object and thus keep those objects from being collected. But as long as you still need those objects that's quite alright.
Any static
field that references an object will prevent that object from being collected, since static
fields are associated with the Type
object for a class. Those in turn are associated with an AppDomain
, and thus will serve as GC roots.
For strings
, it is dependent on whether or not it has been interned. If it has, then the intern pool for the current AppDomain
will reference it and thus prevent collection. If not, then a string
will behave like any other class object, and be eligible for collection when it is no longer accessible via a chain of references from a GC root.
Note that in both cases, if the AppDomain
is unloaded, the objects will become eligible for collection.
No, the garbage collector will not collection the static fields. in general the garbage collection will not collection you classes as long as an instance of your class exists and is pointed to it will stay.
精彩评论