1

I want have to write some tool that dynamically load classes. So I have to call Class.forName function for that. There can be a lot of classes - about 10000. Is it possible to free memory after all they are loaded and not needed?

Cherry
  • 31,309
  • 66
  • 224
  • 364
  • 6
    You can do this by using a different classloader to load those classes. When your process finishes (and those classes don't have any memory leaks), the GC will recycle the classes, including the classloader. This is what most application servers or web containers do. They load an application, and when it's undeployed, it recovers all the memory. – Augusto Sep 17 '13 at 13:22
  • I would avoid creating and loading 10,000 classes. Perhaps there is an abstraction you are missing, or libraries which can be made shared so they are only loaded once. – Peter Lawrey Sep 17 '13 at 13:25
  • possible duplicate of [Unloading classes in java?](http://stackoverflow.com/questions/148681/unloading-classes-in-java) – Ravi Wallau Sep 17 '13 at 13:26
  • Another possible answer: http://stackoverflow.com/questions/2095974/how-to-unload-a-already-loaded-class-in-java – Ravi Wallau Sep 17 '13 at 13:26
  • Are we really talking about 10,000 different classes? or 10,000 different objects or instances? Big difference here. – Nick Sep 17 '13 at 13:45

1 Answers1

0

The question could perhaps do with some clarification. Is the OP loading instances of a Class or Class definitions?

If the question concerns instances then as Clement Berthou says, all you need to do is dereference the created instances and they should eventually be garbage collected. You can request garbage collection at any time by calling System.gc().

For class definitions I think the situation is the same but with a slight variation. Even if all instances of the class have been dereferenced there may still be a reference from the originally loading ClassLoader.

Therefore, I think that you will need to dereference the ClassLoader used to load the Class definitions, in order to make the class definitions available for garbage collection. I don't know for sure though, last time I looked at classloading directly was a long time ago.