I have a Java application (say X) whose performance (time taken to run the application) has to be logged in a text file along with the specified VM Arguments. Performance of my application will vary as we change the maximum Heap Size. So, my requirement is to start the application X from another program (java or python or shell script) with one set of VM argument(say Xmx50M), perform the operations, log the time, shut it down and then perform the same set of operations with a different VM argument. I have to do this multiple times for multiple VM arguments. I am not sure how can I do this. I have read various threads here and blogs but couldn't find anything which could let me shut and then restart the application with different set of VM arguments. I have also tried using shutdown hooks but that didn't help. I guess I am doing something wrong in the usage.
public static void restartApplication() throws IOException {
try {
String java = System.getProperty("java.home") + "/bin/java";
List<String> vmArguments = ManagementFactory.getRuntimeMXBean()
.getInputArguments();
StringBuffer vmArgsOneLine = new StringBuffer();
for (String arg : vmArguments) {
if (!arg.contains("-agentlib")) {
vmArgsOneLine.append(arg);
vmArgsOneLine.append(" ");
}
}
final StringBuffer cmd = new StringBuffer("\"" + java + "\" "
+ vmArgsOneLine);
String[] mainCommand = System.getProperty("sun.java.command")
.split(" ");
if (mainCommand[0].endsWith(".jar")) {
cmd.append("-jar " + new File(mainCommand[0]).getPath());
} else {
cmd.append("-cp \"" + System.getProperty("java.class.path")
+ "\" " + mainCommand[0]);
}
for (int i = 1; i < mainCommand.length; i++) {
cmd.append(" ");
cmd.append(mainCommand[i]);
}
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
Runtime.getRuntime().exec(cmd.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
});
System.exit(0);
} catch (Exception e) {
throw new IOException(
"Error while trying to restart the application", e);
}