views:

328

answers:

2

I'm looking at the possibility of generating Java byte code at run time (hopefully directly in memory rather than via class files, though I imagine that won't make a difference to my question).

I understand this can be done, the question is, does the garbage collector sweep up no-longer-used code? I remember some years ago seeing it claimed that it did not, but I can't now find any references to the topic.

To clarify the purpose of this, I certainly wouldn't bother for ordinary data processing scenarios. But consider genetic programming: potentially billions of small programs generated and run for trillions of executions; in that scenario it's worth trying to make things run as fast as possible, and freeing up no longer used code is important. I'm trying to do something more complex, but it has similarities to genetic programming.

+4  A: 

Classes are tied to the ClassLoader that loaded them. To cause the JVM to collect unused classes, you have to clear all references to the classloader. This is how application servers work with "hot deploy", and it's probably instructive to look at the JBoss or Tomcat implementations if you're not familiar with classloaders (I haven't looked at either, so can't point you to them).

I'm wondering, however, if this is really going to be an issue? How many classes do you plan on creating, how large will they be, and how long will they live? If you have a lot of large classes (say 50k of bytecode or more), and they'll live a short time, then it makes sense to clean them up. Otherwise, not so much.

Also, why are you creating classes? Is it something that you can do with a scripting language (eg Rhino) from within the JVM? Or a home-built interpreter? If yes, then that would solve your class management issues without code.

kdgregory
A: 

If you mean does the class get unloaded by the garbage collector, then no it doesn't.

You can however achieve this by writing a custom class loader.

Nick Holt