changing code while program is running

B

blacky

Hello,

I would like to have my class code loaded into application, which is
already running. I tried something like this:

public class Main
{

...


private void reloadClass() throws Exception
{
new Pair("","").print(); //class to be reloaded
System.in.read (); //interval - here comes manual class recompilation
ClassLoader.getSystemClassLoader ().loadClass ("Pair"); //reload class
new Pair("","").print(); //check if new version loaded
}
}

It seems that ClassLoader.loadClass checks the presence of the Pair
class in memory and doesn't relod it. How to omit it?

regards

blacky
 
M

Matt Humphrey

blacky said:
Hello,

I would like to have my class code loaded into application, which is
already running. I tried something like this:

public class Main
{

...


private void reloadClass() throws Exception
{
new Pair("","").print(); //class to be reloaded
System.in.read (); //interval - here comes manual class recompilation
ClassLoader.getSystemClassLoader ().loadClass ("Pair"); //reload class
new Pair("","").print(); //check if new version loaded
}
}

It seems that ClassLoader.loadClass checks the presence of the Pair
class in memory and doesn't relod it. How to omit it?

You can't. Even if you could, there is no way to automatically migrate the
objects of the earlier class to be instances of the new class because there
is no way to ensure they are compatible.

What I think you can do, however (I havn't tried this), is to use the same
technique that app servers use to reload web app servlets (also JServ and
JUnit)without reloading the JVM . To do this, first don't let your classes
be loaded by the system class loader. Instantiate and use a separate one.
When you want to reload a class, discard (or cease to use) the objects of
the original class, unload the old class loader, instantiate a new
classloader (with a unique id / instance) and use this new class loader to
load the class again. The loaded class will be distinct from the prior
version. Then reload your data using whatever migration policy you need to
have. (E.g. reload from database, re-read XML, etc.) Presuming no
properties were changed, it's not clear to me if you can deserialize data to
the new class. (Changing properties will definately break serialization.)

There may be better ways to do this.

http://archives.java.sun.com/cgi-bin/wa?A2=ind0003&L=servlet-interest&D=0&P=
109117

http://www.artima.com/insidejvm/ed2/

Cheers,
Matt Humphrey (e-mail address removed) http://www.iviz.com/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top