Explore Java Hot Deployment

Source: Internet
Author: User
Tags class definition

# Preface

In the previous article of the ClassLoader JVM, we said that the hot deployment can be implemented by modifying the default ClassLoader, but in the Java development realm, hot deployment has always been a difficult problem, the current Java virtual machine can only implement the method body modification hot deployment, for the entire class structure modification, You still need to restart the virtual machine to reload the class to complete the update operation. For some large applications, it takes a lot of time to restart each reboot, so if you can update a class without restarting the virtual machine as we said before, it becomes important in some business scenarios. For example, many scripting languages support hot-swapping, such as PHP, as long as the PHP source file is replaced, and the change takes effect immediately without restarting the server.

Today we are going to have a simple thermal deployment, note: Do not underestimate him, this is also the way JSP support the implementation of the modification.

# # # 1. How to do it?

In the previous article, we posted a picture:

We know that a class loader can only load a class with the same name, at the Java default ClassLoader level, if it already has the class, it is no longer repeated loading, if you force bypass the judgment and use the custom ClassLoader to repeat the load (such as calling the DefineClass method), the JVM will throw Linkageerror:attempted duplicate class definition for name.

Note, however, that we say that the same class loader cannot load two classes with the same name, but different ClassLoader can load classes with the same name, and after loading, these two classes are not the same class object and cannot be converted, although they do have the same name.

So can we use this feature to implement thermal deployment? As a step: using a custom ClassLoader, loading a class, when a replacement class is needed, we discard the previous class loader and class, use the new ClassLoader to load the new class file, and then run the new object's method.

Let's follow this idea to write a piece of code to try it!

 classAccountmain { Public Static void Main(string[] args)throwsClassNotFoundException, Interruptedexception, Illegalaccessexception, Instantiationexception, Nosuchmethodexception, InvocationTargetException { while(true) {ClassLoader loader =NewClassLoader () {@Override         PublicClass<?>LoadClass(String name)throwsclassnotfoundexception {Try{String FileName = name.substring(name.lastIndexOf(".") +1) +". Class"; InputStream is =GetClass().getResourceAsStream(FileName);if(IS = =NULL) {return Super.LoadClass(name); }byte[] B =New byte[IS.available()]; Is.Read(b);return DefineClass(Name, B,0B.length); }Catch(IOException e) {e.Printstacktrace();Throw NewClassNotFoundException (name);            }        }      }; Class clazz = loader.LoadClass("Cn.think.in.java.clazz.loader.asm.Account"); Object account = Clazz.newinstance(); Account.GetClass().GetMethod("Operation",Newclass[]{}).Invoke(account); Thread.Sleep(20000); }  }}

The above class is a Mian method class, which is a dead loop that is 20 seconds apart, with the following steps:

    1. To create a custom ClassLoader object, the steps to load the class do not follow the parent delegation model, but instead load directly.
    2. Loads the specified class using the class loader you just created.
    3. Get just the class object, use reflection to create the object, and call the object's Operation method.

Why is it 20 seconds apart? Because we are going to modify the class after startup, and recompile. So it takes 20 seconds.

And look at the account class:

publicclass Account {  publicvoidoperation() {    System.out.println("operation...");    try {      Thread.sleep(10);    catch (Exception e) {      e.printStackTrace();    }  }}

This class is very simple, there is only one way to print operation ... String.

We also need a class, what to do with it? We just said that we need to modify the account class and recompile, for the sake of convenience, we create a class that is specifically used to execute the modified account class, because it is definitely recompiled after execution, save us to the command line to use Javac.

The code is as follows:

class ReCompileAccount {  publicstaticvoidmain(String[] args) {    newAccount().operation();  }}

How to test it?

    1. Start the Accountmain Main method. Will immediately print out the operation ... String and starts to wait 20 seconds.
    2. The string that modifies the account class is operation.....new,
    3. Start the Recompileaccount class in order to recompile the Accoutn class.
    4. Wait for the Accountmain class to print.

Without an accident, the final result would be as follows:

See, we have successfully modified the Accout class and implemented a hot deployment without restarting the JVM. As we just said, JSP support modification is also implemented, each JSP page corresponds to a classloader, when the JSP page is modified, re-create the class loader, and then use the new class loader to load the JSP (JSP is actually Java class).

# # # Summary

Based on the principle of ClassLoader, we implemented the Java level of the thermal deployment, but if you implement it again, still feel very troublesome, admittedly, JSP use this way is not a problem, because he is automatically compiled. But if we use our own application, do we have to recompile the class every time we change it, and then replace it at a given time? Can we hand over all this manual work to the JVM? In fact, Tocmat has also been implemented in this way. Confined to space, we'll cover it in the next article.

Good luck!!!!!

Explore Java Hot Deployment

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.