Mike
Mike

Reputation: 60771

Java, runtime class reloading

I am looking for a way to reload a class into Java at runtime. The motivation is to make debugging more efficient. The application is a typical client/server design that synchronously processes requests. A "handler" object is instantiated for each request. This is the only class I intend to dynamically replace. Since each request deals with a fresh instance, reloading this class won't have any side-effects. In short, I do not want to restart the entire application every time there is a change to this module.

In my design, the Java process becomes aware that a .class file has been updated in the classpath in between requests. When this happens, the "handler" class is unloaded and a new one is loaded.

I know I can use the classLoader interface to load in a new class. I seem to be having trouble finding the proper way of "unloading".

Upvotes: 2

Views: 1520

Answers (3)

samarjit samanta
samarjit samanta

Reputation: 1315

As of 2015 also java's class reloading is a missing feature.

  • Use OSGi to create a class reloading application.
  • Use jrebel for testing. There are a few others which does the same thing.
  • Use application server and externalize the parts which you want to reload into a separate web application. Then keep deploying/undeploying. You will eventually get some perm gen space overflow kind of errors due to dangling old ClassLoader instances.
  • Use a script runner to execute parts of changeable code. JSR-223 Java Scripting API support for the scripting language "Java".

I had written a series about class reloading. But all of those methods are not good for production.

IMHO this class reloading is messy in java and its not worth trying it. But I would very much like this to be a specification in java.

Upvotes: 0

djna
djna

Reputation: 55907

I believe that you actually need to have a hierarchy of classloaders, and in order to reload you actually get rid of the low level classloader (by normall GC means), and hence all the classes it loaded. So far as I know this technique is used by Java EE app servers for reloading applications, and there's all manner of fun results when framework code loaded in one classloader wants to use classes loaded somewhere else.

Upvotes: 1

Michael Borgwardt
Michael Borgwardt

Reputation: 346300

Classes will be unloaded and garbage collected like any other object, if there is no remaining reference to them. That means there must be no reachable instance of the class (as loaded by that particular classloader instance) and the classloader instance itself must be eligible for garbage collection as well.

So basically, all you have to do is to create a new classloader instance to load the new version of the class, and make sure that no references to instances of the old version remain.

Upvotes: 4

Related Questions