通过热交换机制在运行时更改方法 [英] Change a method at runtime via a hot swap mechanism

查看:125
本文介绍了通过热交换机制在运行时更改方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个简单的Java程序,它只包含一个类:

Assume we have a trivial Java program that consists of just one class:

public class HelloWorld {

   private static void replacable(int i) {
      System.out.println("Today is a nice day with a number " + i);
   }        

   public static void main(String[] args) throws Exception {
      for(int i = 0; i < 100000; ++i) {
      replacable(i);
      Thread.sleep(500);
   }
}

在编译并运行之后,输出将是:

After it's compiled and run, output will be this:


今天是一个美好的一天,数字为0

Today is a nice day with a number 0

今天是个不错的选择数字1的一天

Today is a nice day with a number 1

今天是一个美好的一天,数字2

Today is a nice day with a number 2

今天是美好的一天数字3

Today is a nice day with a number 3

...

我的问题:是否存在(或者是否在地平线上)某种方式在运行时交换可替换的方法?使用新版本的 replacable 编写另一个版本的 HelloWorld 之类的东西,编译它然后再编译旧版本运行JVM?

My question: does there exist (or is there on the horizon) some way to swap replacable method at runtime? Something like writing another version of HelloWorld with a new version of replacable, compiling it and then the old version in an already running JVM?

所以,如果我写这样的新版本:

So, if I write the new version like this:

private static void replacable(int i) {
   System.out.println("Today is an even nicer day with a number " + i);
}  

有类似于 Erlang的热门代码交换我可以这样做:

is there something similar to Erlang's hot code swapping where I can do this:


  1. 运行原始程序

  2. 编写修改版本

  3. 使用命令行程序,连接到运行JVM并替换现有方法

因此,在运行期间,这将会发生:

so that, during runtime, this will happen:


今天是一个美好的一天,数字15000

Today is a nice day with a number 15000

今天是一个美好的一天,数字15001

Today is a nice day with a number 15001

今天是一个更好的一天,数字15002

Today is an even nicer day with a number 15002

今天是一个更好的日子,数字15003

Today is an even nicer day with a number 15003

...

假设上面的程序是独立的,在标准的Java SE环境中运行,类路径上没有别的东西,所以它几乎是一个Hello世界风格的节目。

Assume that above program is standalone, runs in a standard Java SE environment, there is nothing else on classpath, so it's almost a Hello world style program.

注意:我知道这个技术像字节码操作( cglib ), aspectJ jRebel JMX ,存在Java EE等方法的热点,但它们并不是我想到的。想想Erlang。

Note: I know that technologies like bytecode manipulation (cglib), aspectJ, jRebel, JMX, hotswapping of methods in Java EE etc. exist, but they aren't what I'm thinking of. Think of Erlang.

推荐答案

你可以使用开源 HotSpot VM 或商业 JRebel IDE插件可轻松实现您的目标(查看比较表这里)。

You can either use the open-source HotSpot VM or the commercial JRebel IDE plugin to easily achieve your goal (view comparison table here).

这篇关于通过热交换机制在运行时更改方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆