5

The answer to 'unloading classes in java' says -

"The only way that a Class can be unloaded is if the Classloader used is garbage collected." I took a look at the JLS but couldn't understand it

Why is this the case?

Community
  • 1
  • 1
Everyone
  • 2,366
  • 2
  • 26
  • 39

1 Answers1

13

A class is only unloaded when it is garbage collected, and for that to happen there must be no references to it anywhere. And the classloader keeps a reference to each class it loads.

Nick Moore
  • 15,547
  • 6
  • 61
  • 83
  • 2
    And why does it keep a reference? – Mnementh Mar 31 '10 at 08:20
  • @Mnementh - Is it for reinstantiation if so desired? – Everyone Mar 31 '10 at 08:49
  • 3
    It keeps a ref to it so if it is asked to load it again it can just return the same one. Otherwise you would have multiple instances of the same class object being loaded with different refs to them floating around. – Nick Moore Mar 31 '10 at 08:57
  • 3
    Well it could keep only a weak reference to the class to prevent the case of different versions of the same class floating around, but still allow class unloading. Then, however, statics wouldn't work as expected - if you modify a static, you would expect that modification to survive "forever" - if a class was garbage collected while the loader was around, a later recreation of the class would have the static "reset". – BeeOnRope Jun 26 '11 at 02:18