Site icon JVM Advent

(Re)Start me up!

There are cases where you would like to start a Java process identical to the current one (or at least using the the same JVM with tweaked parameters). Some concrete cases where this would be useful:

Doing this is relatively simple – and can be done in pure Java – after you find the correct API calls:


List<String> arguments = new ArrayList<>();
// the java executable
arguments
.add(String.format("%s%sbin%sjava",
System.getProperty("java.home"), File.separator,
File.separator));
// pre-execuable arguments (like -D, -agent, etc)
arguments.addAll(ManagementFactory.getRuntimeMXBean()
.getInputArguments());

String classPath = System.getProperty("java.class.path"), javaExecutable = System
.getProperty("sun.java.command");
if (classPath.equals(javaExecutable)) {
// was started with -jar
arguments.add("-jar");
arguments.add(javaExecutable);
} else {
arguments.add("-classpath");
arguments.add(classPath);
arguments.add(javaExecutable);
}

// we might add additional arguments here which will be received by the
// launched program
// in its args[] paramater
arguments.add("runme");

// launch it!
new ProcessBuilder().command(arguments).start();

Some explanations about to the code:

This is it! After that we use ProcessBuilder (which we should always favour over Runtime.exec because it auto-escapes the parts of the command line for us).

A final thought: if you intend to use this method to “daemonize” a process (that is: to ensure that it stays running after its parent process has terminated) you should do two things:

This is it for today, hope you enjoyed it, fond it useful. If you run the code and it doesn’t work as advertised, let me know so that I can update it (I’m especially interested if it works with non Sun/Oracle JVMs). Come back tomorrow for an other article!

Meta: this post is part of the Java Advent Calendar and is licensed under the Creative Commons 3.0 Attribution license. If you like it, please spread the word by sharing, tweeting, FB, G+ and so on! Want to write for the blog? We are looking for contributors to fill all 24 slot and would love to have your contribution! Contact Attila Balazs to contribute!

Author: gpanther

Exit mobile version