DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • From Database Changes to Real-Time Actions at Scale: Oracle GoldenGate and Java
  • Java 27 Makes G1 the Default Everywhere: How to Test Your Small Containers Before You Upgrade
  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop

Trending

  • Kubernetes Rolling Updates Are Lying to You — and Your Users Are Paying for It
  • Slopsquatting: Building a Scanner That Catches AI-Hallucinated Packages Before They Reach Production
  • Architecture Lessons from Two Digital Transformations
  • Adding Graph Retrieval to a RAG Pipeline With Python

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Java
  4. Running a Java Class as a Subprocess

Running a Java Class as a Subprocess

Learn more about how to run a Java class as a subprocess in this quick demonstration.

By 
Dan Newton
·
May. 21, 19 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
48.7K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Running a Java class (not a jar) as a subprocess is something I needed to do this week. More precisely, I wanted to spawn a new process from within a test, instead of running it inside the test directly (in-process). I don’t think this is anything fancy or a complex thing to do. But, this is not something I have ever needed to do before and didn’t know the exact code to write.

Luckily, a quick Google search and a few Stack Overflow posts later, I found the answer I needed. Although the answer is there, I am rewriting it here for my own benefit and as well as yours.

class JavaProcess {

  private JavaProcess() {
  }

  public static int exec(Class clazz, List<String> jvmArgs, List<String> args) throws IOException,
        InterruptedException {
    String javaHome = System.getProperty("java.home");
    String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
    String classpath = System.getProperty("java.class.path");
    String className = clazz.getName();

    List<String> command = new ArrayList<>();
    command.add(javaBin);
    command.addAll(jvmArgs);
    command.add("-cp");
    command.add(classpath);
    command.add(className);
    command.addAll(args);

    ProcessBuilder builder = new ProcessBuilder(command);
    Process process = builder.inheritIO().start();
    process.waitFor();
    return process.exitValue();
  }
}


This static function takes in the Class that you want to execute along with any JVM arguments and arguments that the class’s main method is expecting. Having access to both sets of arguments allows full control over the execution of the subprocess. For example, you might want to execute your class with a low heap space to see how it copes under memory pressure (which is what I needed it for).

Note, for this to work, the class that you want to execute needs to have a main method. This is kind of important.

Accessing the path of the Java executable (stored in javaBin) allows you to execute the subprocess using the same version of Java as the main application. If javaBin was replaced by "java", then you run the risk of executing the subprocess with your machine’s default version of Java. That is probably fine, a lot of the time. But, there are likely to be situations where this is not desired.

Once the commands are all added to the command list, they are passed to the ProcessBuilder. The ProcessBuilder takes this list and uses each value contained in it to generate the command. Each value inside the command list is separated with spaces by the ProcessBuilder. There are other overloads of its constructor, one of which takes in a single string where you can manually define the whole command yourself. This removes the need for you to manually manage the addition of arguments to the command string.

The subprocess is started with its IO passing up to the process that executed it. This is required to see both any stdouts and stderrs it produces. inheritIO is a convenience method and can also be achieved by calling chaining the following code instead (also configures the stdin of the subprocess):

builder
    .redirectInput(ProcessBuilder.Redirect.INHERIT)
    .redirectOutput(ProcessBuilder.Redirect.INHERIT)
    .redirectError(ProcessBuilder.Redirect.INHERIT);


Finally waitFor tells the executing thread to wait for the spawned subprocess to finish. It does not matter if the process ends successfully or errors — as long as the subprocess finishes somehow. The main execution can carry on going. How the process finished is detailed by its exitValue. For example, 0 normally denotes a successful execution and 1 details an invalid syntax error. There are many other exit codes and they can all vary between applications.

Calling the exec method would look something like the below:

JavaProcess.exec(MyProcess.class, List.of("-Xmx200m"), List.of("argument"))


This executes the following command (or something close to it):

/Library/Java/JavaVirtualMachines/jdk-12.0.1.jdk/Contents/Home/bin/java -cp /playing-around-for-blogs MyProcess "argument"


I have cut out a lot of the paths included classpath to keep it a bit tidier. Yours will probably look much longer than this. It really depends on your application. The path in the command above is the bare minimum needed to get it to run (obviously customized for my machine).

The exec method is reasonably flexible and helpful in describing what is going on. Although, if you wish to make it more malleable and applicable in a wider range of situations, I recommend returning the ProcessBuilder itself from the method. Allowing you to reuse this piece of code in several places while providing the flexibility to configure the IO redirects as well as the power to decide whether to run the subprocess in the background or block and wait for it to finish. This would look something like:

public static ProcessBuilder exec(Class clazz, List<String> jvmArgs, List<String> args) {
  String javaHome = System.getProperty("java.home");
  String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
  String classpath = System.getProperty("java.class.path");
  String className = clazz.getName();

  List<String> command = new ArrayList<>();
  command.add(javaBin);
  command.addAll(jvmArgs);
  command.add("-cp");
  command.add(classpath);
  command.add(className);
  command.addAll(args);

  return new ProcessBuilder(command);
}


By utilizing either (or both) of these functions, you will now have the ability to run any class that exists in your application’s classpath. In my situation, this was very helpful in spawning subprocesses inside of an integration test without needing to pre-build any jars. This allowed control over JVM arguments, such as the memory of the subprocesses, which would not be configurable if run directly inside the existing process.

If you enjoyed this post or found it helpful (or both), then please feel free to follow me on Twitter at @LankyDanDev, and remember to share with anyone else who might find this useful!

Java (programming language)

Published at DZone with permission of Dan Newton. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • From Database Changes to Real-Time Actions at Scale: Oracle GoldenGate and Java
  • Java 27 Makes G1 the Default Everywhere: How to Test Your Small Containers Before You Upgrade
  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook