The question is rather simple. How can I start a main method in another java process? Now I do it like this:
startOptions = new String[] {"java", "-jar", "serverstart.jar"};
new ProcessBuilder(startOptions).start();
But they asked me to do it not with an external .jar file. The serverstart.jar obviously has a main method, but it it possible to call that main method in another process, without calling the .jar file?
I'm thinking of something like this:
new ProcessBuilder(ServerStart.main(startOptions)).start();
But I don't know if anything like that exists.
Kind regards,
I would suggest invoking a shellscript from java and using it to start the new process (if you cant live with just another thread at all).
Assuming a new thread with a new classloader is not enough (I would vote for this solution though), I understand you need to create a distinct process that invokes a main method in a class without having that declared as "jar main method" in the manifest file -- since you don't have a distinct serverstart.jar anymore.
In this case, you can simply call
java -cp $yourClassPath your.package.ServerStart
, as you would do for running any java application when you don't have (or don't want to use) the manifest Main-Class.You can do this using Reflection (java.lang.reflect package).
I'll answer here how to create multi process application without spring :). With spring you can do this by xml config. Multithread is another story, this is multi-process
Create a JavaProces class as seen below. You can store a counterparter XML/JSON of this class in your environment. Then start your process with
Runtime.getRuntime().exec(processRunnerString);
,You should first find
java.exe
,vm args
, then set-classpath
thenmainClass
andargs
respectively.You can use
JMX
to communicate with other process.Determine location of java.exe from java.home env. variable
Creating a new "java" process from java is not possible since two processes can't share one JVM. (See this question and the accepted answer).
If you can live with creating a new
Thread
instead of aProcess
you can do it with a customClassLoader
. It is as close you can get to a new process. All static and final fields will be reinitialized!Also note that the
"ServerStart
class (for the example below) must be in the class path of the current executing JVM):And this is the custom class loader: