Note that there are some explanatory texts on larger screens.

plurals
  1. POChange a method at runtime via a hot swap mechanism
    text
    copied!<p>Assume we have a trivial Java program that consists of just one class:</p> <pre><code>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 &lt; 100000; ++i) { replacable(i); Thread.sleep(500); } } </code></pre> <p>After it's compiled and run, output will be this:</p> <blockquote> <p>Today is a nice day with a number 0</p> <p>Today is a nice day with a number 1</p> <p>Today is a nice day with a number 2</p> <p>Today is a nice day with a number 3</p> <p>...</p> </blockquote> <p>My question: does there exist (or is there on the horizon) some way to swap <code>replacable</code> method at runtime? Something like writing another version of <code>HelloWorld</code> with a new version of <code>replacable</code>, compiling it and then the old version in an already running JVM?</p> <p>So, if I write the new version like this:</p> <pre><code>private static void replacable(int i) { System.out.println("Today is an even nicer day with a number " + i); } </code></pre> <p>is there something similar to <a href="http://spawnlink.com/articles/rules-of-hot-code-swapping/">Erlang's hot code swapping</a> where I can do this:</p> <ol> <li>run original program</li> <li>write modified version</li> <li>using a command line program, connect to running JVM and replace existing method</li> </ol> <p>so that, during runtime, this will happen:</p> <blockquote> <p>Today is a nice day with a number 15000</p> <p>Today is a nice day with a number 15001</p> <p>Today is an even nicer day with a number 15002</p> <p>Today is an even nicer day with a number 15003</p> <p>...</p> </blockquote> <p>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.</p> <p>Note: I know that technologies like bytecode manipulation (<a href="http://cglib.sourceforge.net/">cglib</a>), <a href="http://www.eclipse.org/aspectj/">aspectJ</a>, <a href="http://www.zeroturnaround.com/jrebel/">jRebel</a>, <a href="http://java.sun.com/javase/technologies/core/mntr-mgmt/javamanagement/">JMX</a>, hotswapping of methods in Java EE etc. exist, but they aren't what I'm thinking of. Think of Erlang.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload