Java ProcessHandle start JVM to run job

Description

Java ProcessHandle start JVM to run job

import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

class Job {/*from  w ww  .j av a  2  s  .  c  om*/
  /**
   * Starts a new JVM to run the Job class.
   */
  public static Process startProcess(long sleepInterval, long sleepDuration) {
    List<String> cmd = new ArrayList<>();
    addJvmPath(cmd);
    addModulePath(cmd);
    addClassPath(cmd);
    addMainClass(cmd);

    cmd.add(String.valueOf(sleepInterval));
    cmd.add(String.valueOf(sleepDuration));

    ProcessBuilder pb = new ProcessBuilder().command(cmd).inheritIO();
    String commandLine = pb.command().stream().collect(Collectors.joining(" "));
    System.out.println("Command used:\n" + commandLine);

    Process p = null;
    try {
      p = pb.start();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return p;
  }
  private static void addJvmPath(List<String> cmd) {
    String jvmPath = ProcessHandle.current().info().command().orElse("");
    if (jvmPath.length() > 0) {
      cmd.add(jvmPath);
    } else {
      final String FILE_SEPARATOR = System.getProperty("file.separator");
      jvmPath = System.getProperty("java.home") + FILE_SEPARATOR + "bin" + FILE_SEPARATOR + "java";
      cmd.add(jvmPath);
    }
  }
  private static void addModulePath(List<String> cmd) {
    String modulePath = System.getProperty("jdk.module.path");
    if (modulePath != null && modulePath.trim().length() > 0) {
      cmd.add("--module-path");
      cmd.add(modulePath);
    }
  }
  private static void addClassPath(List<String> cmd) {
    String classPath = System.getProperty("java.class.path");
    if (classPath != null && classPath.trim().length() > 0) {
      cmd.add("--class-path");
      cmd.add(classPath);
    }
  }
  private static void addMainClass(List<String> cmd) {
    Class<Job> cls = Job.class;
    String className = cls.getName();
    Module module = cls.getModule();
    if (module.isNamed()) {
      String moduleName = module.getName();
      cmd.add("--module");
      cmd.add(moduleName + "/" + className);
    } else {
      cmd.add(className);
    }
  }
}

public class Main {
  public static void main(String[] args) {
    Process p = Job.startProcess(5, 15);
    if (p == null) {
      System.out.println("Could not create a new process.");
      return;
    }

    // Get the handle of the current process
    ProcessHandle handle = p.toHandle();

    // Print the process details
    printInfo(handle);

    CompletableFuture<ProcessHandle> future = handle.onExit();

    // Print a message when process terminates
    future.thenAccept((ProcessHandle ph) -> {
      System.out.printf("Job (pid=%d) terminated.%n", ph.pid());
    });

    try {
      // Wait for the process to complete
      future.get();
    } catch (InterruptedException | ExecutionException e) {
      e.printStackTrace();
    }

    // Print process details again
    printInfo(handle);
  }

  public static void printInfo(ProcessHandle handle) {
    // Get the process ID
    long pid = handle.pid();

    // Is the process still running
    boolean isAlive = handle.isAlive();

    // Get other process info
    ProcessHandle.Info info = handle.info();
    String command = info.command().orElse("");

    String[] args = info.arguments().orElse(new String[] {});

    String commandLine = info.commandLine().orElse("");

    ZonedDateTime startTime = info.startInstant().orElse(Instant.now()).atZone(ZoneId.systemDefault());

    Duration duration = info.totalCpuDuration().orElse(Duration.ZERO);

    String owner = info.user().orElse("Unknown");
    long childrenCount = handle.children().count();

    // Print the process details
    System.out.printf("PID: %d%n", pid);
    System.out.printf("IsAlive: %b%n", isAlive);
    System.out.printf("Command: %s%n", command);
    System.out.printf("Arguments: %s%n", Arrays.toString(args));
    System.out.printf("CommandLine: %s%n", commandLine);
    System.out.printf("Start Time: %s%n", startTime);
    System.out.printf("CPU Time: %s%n", duration);
    System.out.printf("Owner: %s%n", owner);
    System.out.printf("Children Count: %d%n", childrenCount);
  }
}



PreviousNext

Related