Maybe java.lang.Process could help here ..

The ProcessBuilder.start() and Runtime.exec methods create a native process and return an instance of a subclass of Process that can be used to control the process and obtain information about it. The class Process provides methods for performing input from the process, performing output to the process, waiting for the process to complete, checking the exit status of the process, and destroying (killing) the process.

Answer from miku on Stack Overflow
🌐
Oracle
docs.oracle.com › en › java › javase › 22 › core › creating-process.html
Creating a Process
July 11, 2024 - To create a process, first specify the attributes of the process, such as the command's name and its arguments, with the ProcessBuilder class. Then, start the process with the ProcessBuilder.start method, which returns a Process instance.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › Process.html
Process (Java Platform SE 8 )
April 21, 2026 - There is no requirement that a process represented by a Process object execute asynchronously or concurrently with respect to the Java process that owns the Process object. As of 1.5, ProcessBuilder.start() is the preferred way to create a Process.
🌐
TutorialsPoint
tutorialspoint.com › home › articles on trending technologies › create a process using processbuilder in java 9
How to create a process using ProcessBuilder in Java 9
April 20, 2020 - In the below example, we can create a process of "notepad" application by using the ProcessBuilder class. import java.time.ZoneId; import java.util.stream.Stream; import java.util.stream.Collectors; import java.io.IOException; public class ProcessBuilderTest { public static void main(String args[]) throws IOException { ProcessBuilder pb = new ProcessBuilder("notepad.exe"); String np = "Not Present"; Process p = pb.start(); ProcessHandle.Info info = p.info(); System.out.printf("Process ID : %s%n", p.pid()); System.out.printf("Command name : %s%n", info.command().orElse(np)); System.out.printf("
🌐
DEV Community
dev.to › dbillion › understanding-java-processes-53j0
Understanding Java Processes - DEV Community
May 5, 2024 - It allows Java applications to ... exit value. Creating a new process in Java is straightforward using the Runtime.exec() method or the ProcessBuilder class....
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-lang-process-class-java
Java.lang.Process class in Java - GeeksforGeeks
February 15, 2023 - // Java code illustrating destroyForcibly() // method for windows operating system // Class public class ProcessDemo { // Main driver method public static void main(String[] args) { try { // create a new process System.out.println("Creating Process"); ProcessBuilder builder = new ProcessBuilder("notepad.exe"); Process pro = builder.start(); // wait 10 seconds System.out.println("Waiting"); Thread.sleep(10000); // kill the process pro.destroyForcibly(); System.out.println("Process destroyed"); } catch (Exception ex) { ex.printStackTrace(); } } } Output: Creating Process Waiting Process destroyed ·
🌐
Stack Overflow
stackoverflow.com › questions › 63068015 › create-a-new-process-in-java-exit-the-current-process
Create a new process in Java, exit the current process - Stack Overflow
I tweaked a bit of code and now the program creates the new process, gets IO control and after entering a command, it exits. if(System.getProperty("os.name").contains("Windows")) { //For Windows Builds use this new ProcessBuilder("cmd", "/c", "java Launcher").inheritIO().start(); System.exit(0); } else { //For Linux/Unix or Mac Builds use this long pid = ProcessHandle.current().pid(); System.out.println(pid); String a=String.valueOf(pid); Thread.sleep(10000); System.out.println(new ProcessBuilder("/bin/bash", "-c", "java Launcher").inheritIO().start()); System.exit(1); }
🌐
DZone
dzone.com › coding › java › running a java class as a subprocess
Running a Java Class as a Subprocess
May 21, 2019 - Learn more about how to run a Java class as a subprocess in this quick demonstration, specifically by creating a new process from within a test.
Find elsewhere
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › ProcessBuilder.html
ProcessBuilder (Java Platform SE 8 )
April 21, 2026 - Java™ Platform Standard Ed. 8 ... This class is used to create operating system processes. Each ProcessBuilder instance manages a collection of process attributes. The start() method creates a new Process instance with those attributes.
Top answer
1 of 3
38

http://www.rgagnon.com/javadetails/java-0014.html

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.file.Paths;

public class CmdExec {

public static void main(String args[]) {
    try {
        // enter code here

        Process p = Runtime.getRuntime().exec(
            Paths.get(System.getenv("windir"), "system32", "tree.com /A").toString()
        );

        // enter code here

        try(BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
            String line;

            while ((line = input.readLine()) != null) {
                System.out.println(line);
            }
        }

    } catch (Exception err) {
        err.printStackTrace();
    }
  }
}

You can get the local path using System properties or a similar approach.

http://download.oracle.com/javase/tutorial/essential/environment/sysprop.html

2 of 3
31

The Java Class Library represents external processes using the java.lang.Process class. Processes can be spawned using a java.lang.ProcessBuilder:

Process process = new ProcessBuilder("processname").start();

or the older interface exposed by the overloaded exec methods on the java.lang.Runtime class:

Process process = Runtime.getRuntime().exec("processname");

Both of these will code snippets will spawn a new process, which usually executes asynchronously and can be interacted with through the resulting Process object. If you need to check that the process has finished (or wait for it to finish), don't forget to check that the exit value (exit code) returned by process.exitValue() or process.waitFor() is as expected (0 for most programs), since no exception is thrown if the process exits abnormally.

Also note that additional code is often necessary to handle the process's I/O correctly, as described in the documentation for the Process class (emphasis added):

By default, the created subprocess does not have its own terminal or console. All its standard I/O (i.e. stdin, stdout, stderr) operations will be redirected to the parent process, where they can be accessed via the streams obtained using the methods getOutputStream(), getInputStream(), and getErrorStream(). The parent process uses these streams to feed input to and get output from the subprocess. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, or even deadlock.

One way to make sure that I/O is correctly handled and that the exit value indicates success is to use a library like jproc that deals with the intricacies of capturing stdout and stderr, and offers a simple synchronous interface to run external processes:

ProcResult result = new ProcBuilder("processname").run();

jproc is available via maven central:

<dependency>
      <groupId>org.buildobjects</groupId>
      <artifactId>jproc</artifactId>
      <version>2.5.1</version>
</dependency>
🌐
Oracle
docs.oracle.com › en › java › javase › 13 › docs › api › java.base › java › lang › ProcessBuilder.html
ProcessBuilder (Java SE 13 & JDK 13 )
If the operating system does not support the creation of processes, an UnsupportedOperationException will be thrown. Subsequent modifications to any of the specified builders will not affect the returned Process. ... For example to count the unique imports for all the files in a file hierarchy on a Unix compatible platform: String directory = "/home/duke/src"; ProcessBuilder[] builders = { new ProcessBuilder("find", directory, "-type", "f"), new ProcessBuilder("xargs", "grep", "-h", "^import "), new ProcessBuilder("awk", "{print $2;}"), new ProcessBuilder("sort", "-u")}; List<Process> processes = ProcessBuilder.startPipeline( Arrays.asList(builders)); Process last = processes.get(processes.size()-1); try (InputStream is = last.getInputStream(); Reader isr = new InputStreamReader(is); BufferedReader r = new BufferedReader(isr)) { long count = r.lines().count(); }
🌐
Baeldung
baeldung.com › home › java › core java › guide to java.lang.process api
Guide to java.lang.Process API | Baeldung
June 10, 2025 - In general, our Java application can call upon any application that is running within our computer system, subject to Operating System restrictions. Therefore, we can execute applications. So, let’s see what the different use cases we can run by utilizing the Process API are. In short, the ProcessBuilder class allows us to create subprocesses within our application. Let’s see a demo of opening a Windows-based Notepad application: ProcessBuilder builder = new ProcessBuilder("notepad.exe"); Process process = builder.start();
🌐
ZetCode
zetcode.com › java › processbuilder
Java ProcessBuilder - creating processes in Java
May 1, 2025 - The ProcessBuilder class in Java is used to create and manage operating system processes. It provides a convenient way to execute system commands, manage process environments, and control input/output streams. The start method creates a new Process instance with the following configurable ...
🌐
Krishna Kumar
krishnakumar.hashnode.dev › a-beginners-guide-to-processbuilder-in-java
how processbuilder work in java - Krishna Kumar
February 19, 2023 - The most basic method is to use the start() method, which takes an array of strings as input. This array represents the command that you want to execute, along with any arguments.
🌐
Metasfresh
docs.metasfresh.org › appdictionary_collection › EN › how_to_create_processes.html
How to create a process (Java Client)
Log in to the desired Java back-end instance with the user role “System Administrator”. Open Report & Process from the menu. Click on to create a new process.
🌐
Openbravo
wiki.openbravo.com › wiki › How_to_create_a_Java_Based_Process
How to create a Java Based Process
Authenticate using one of the following domains: external.orisha.com, orisha.com · Google SSO with @orisha.com only
Top answer
1 of 5
9

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 a Process you can do it with a custom ClassLoader. 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):

Copypublic static void main(String args[]) throws Exception {
    // start the server
    start("ServerStart", "arg1", "arg2");
}

private static void start(final String classToStart, final String... args) {

    // start a new thread
    new Thread(new Runnable() {
        public void run() {
            try {
                // create the custom class loader
                ClassLoader cl = new CustomClassLoader();

                // load the class
                Class<?> clazz = cl.loadClass(classToStart);

                // get the main method
                Method main = clazz.getMethod("main", args.getClass());

                // and invoke it
                main.invoke(null, (Object) args);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();
}

And this is the custom class loader:

Copyprivate static class CustomClassLoader extends URLClassLoader {
    public CustomClassLoader() {
        super(new URL[0]);
    }

    protected java.lang.Class<?> findClass(String name) 
    throws ClassNotFoundException {
        try{
            String c = name.replace('.', File.separatorChar) +".class";
            URL u = ClassLoader.getSystemResource(c);
            String classPath = ((String) u.getFile()).substring(1);
            File f = new File(classPath);

            FileInputStream fis = new FileInputStream(f);
            DataInputStream dis = new DataInputStream(fis);

            byte buff[] = new byte[(int) f.length()];
            dis.readFully(buff);
            dis.close();

            return defineClass(name, buff, 0, buff.length, (CodeSource) null);

        } catch(Exception e){
            throw new ClassNotFoundException(e.getMessage(), e);
        }
    }
}
2 of 5
8

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.