5

When do strings and static fields get reclaimed by the garbage collector?

I'm asking this because I know statics in ASP.NET are always live.

Dan J
  • 16,319
  • 7
  • 50
  • 82
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • 2
    For an answer for `static`, see [here](http://stackoverflow.com/questions/6600093/do-static-members-ever-get-garbage-collected) – dlev Jul 29 '11 at 20:24
  • 1
    They are, but not the GC. It takes AppDomain.Unload(). ASP.NET uses ADs heavily, the exact rules are a bit mysterious to me. Hopefully this comment will steer the answers the right way, only the lowest voted answer mentions them. – Hans Passant Jul 29 '11 at 21:50

4 Answers4

5

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.

H H
  • 263,252
  • 30
  • 330
  • 514
Etienne de Martel
  • 34,692
  • 8
  • 91
  • 111
3

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.

H H
  • 263,252
  • 30
  • 330
  • 514
2

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.

dlev
  • 48,024
  • 5
  • 125
  • 132
1

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.

Jalal Said
  • 15,906
  • 7
  • 45
  • 68