13 April 2009

Hotswap Agent for Java Virtual Machine (Part 1)

Before joining my company and in fact until two years after I joined my company, C, 8085/8086 ALP and Perl are the programming languages I knew. I learned C and ALP at college and Perl at my office to write a simple CGI utility. Two years later, I started to learn Java as I was moved to development team and I started to learn Java with certain amount of dislike. After a short period of time, I started to read about Java Virtual Machine specification and writing tools with the help of JPDA. Writing tools using JDI/JPDA is relatively simple as JPDA gives you enough infrastructure. This post contains specification/requirements for writing a small and powerful agent to reload classes of live JVM. As you may know, Java source code is compiled and bytecodes are produced. These bytecodes (generally .class files) are loaded into JVM and are much like machine instruction but the fact is that only JVM can understand it. These bytecodes are your program and decides how your application is executed.

If you are a developer, your daily job might be writing code or fixing bugs or both. During development, you may need to change the logic of your program, recompile the source and restart the application. Restarting the application is stopping the running JVM and starting a new JVM process. This is a very lengthly process if your work involves changes to source code multiple times. Sun HotSpot VM comes with a feature called HotSwap. Using this feature one can replace the classes that are loaded in the JVM. Once reloaded, the objects that are already created also takes effect with new changes. This tool will improve the productivity of developers when frequent restart of the applications is required. Here is the specification.

Specification
Write a simple tool which let you to reload classes in a running JVM without restarting your application. Also provide a simple user interface (probably using SWING).

Steps
1. Use Java Debug Interface API to connect to remote JVM. In order to connect to remote JVM, you the hostname/ip address of the remote box and port number on which your JVM runs. In order to hotswap the classes, you need start JVM in debug mode and if you start JVM using "socket" debugger.

2. Also subscribe for few important events such as JVM Exit, Disconnect Event. (for more info refer Java Debug Interface API Spec).

3. If the connection is successful, you get an instance of the remote JVM and you can once again use JDI to replace classes.

4. You have to write the logic of reading the class file (flat file) from the file system and give to JDI. JDI pumps the class file to remote JVM which reloads the class after making lot of checks.

In next couple of days, I m planning to write a post on how to do this with a small example (thanks to Veeru for pointing this out).