How to run a Java program multiple times without JVM exiting?

无人久伴 提交于 2019-12-13 15:35:52

问题


Suppose I have a Java program Test.class, if I used the below script

for i in 1..10
do
    java Test
done

the JVM would exit each time java Test is invoked.

What I want is running java Test multiple times without exiting the JVM, so that, the optimized methods in prior runs can be used by later runs, and possibly be further optimized.


回答1:


public class RunTest
 {
    public static void main(String[] args)
      {
          for(int i=1; i<=10; i++)
              Test.main(args); 
      }
 }

This should do it. You can call the Test class' main function with the same arguments you pass to your main function. This is the "wrapper" that another poster referred to.




回答2:


Why not write a Java program that repeatedly calls the entry point of the program you want to run?




回答3:


Run this once

java Run

The main Program calling your Test class mulitple times.

class Run {

    public static void main(String[] args) {
        for(int i=0; i<10; i++){
            Test.main(args);
        }
    }
}



回答4:


Use code like this:

public static void main2(String args[]){ // change main to main2
  for(int i=0;i<10;i++)main(args);
}
public static void main(String args[]){ // REAL main
   //...
}



回答5:


What you want to do is put the loop inside the Test class or pass the number of times you want to loop as an argument to the main() inside Test.

NOTE:

If you are looking at JIT optimizations it will take more than 10 iterations to kick in.




回答6:


Perhas a ProcessBuilder would be suitable? E.g., something like

String[] cmd = {"path/to/java", "test"};
ProcessBuilder proc = new ProcessBuilder(cmd);
Process process = proc.start();



回答7:


Same as previous examples but using command line args

public class Test {

    public static void main(String[] args) {
        if ( args.length > 0) {
            final Integer n = Integer.valueOf(args[0]);
            System.out.println("Running test " + n);
            if ( n > 1 ) {
                main(new String[] { Integer.toString(n-1) });
            }
        }
    }
}

use the args to indicate the number of runs

$ java Test 10


来源:https://stackoverflow.com/questions/11992198/how-to-run-a-java-program-multiple-times-without-jvm-exiting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!