Saturday, July 12, 2008

JVM it too Hot with HotSwap

Right from my first encounter JVM, it amazed me. Before working on Java, I never got a chance to read the internals of any interpreter. I started to read the internals of JVM and roughly three years before I read about Java Platform Debug Architecture. I tried writing simple debugger agent using Java Virtual Machine Tool Interface, Java Virtual Machine Debug/Profile Interface (both deprecated) and Java Debug Interface.

Apart from being specifications and methodologies to write tools, these specification can help you a lot to understand JVM deeply. Recently, I was reading through HotSwap and suddenly wanted to write a simple tool using which I can reload classes in a live remote JVM. I was successful in loading the class. The only disadvantage is that you cannot reload the class if you have added any new members to it. However, this is the limitations of JVM which may be addressed in upcoming Java major release. The rest of this write up gives you, the specification and algorithm (simple steps) used.

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.

No comments: