Dann
Dann

Reputation: 65

Get memory usage and execution time from a process initiated with the ProcessBuilder

I'm working in a code executor in Java. The problem is how to control the execution time and memory usage of this execution.

I'm doing something like this:

public ExecutionResult execute(List<String> args, String inputFile) throws CommandLineExecutorException {
    try {
        ProcessBuilder builder = new ProcessBuilder(args);
        if (inputFile != null) {
            builder.redirectInput(new File(inputFile));
        }

        final long startTime = System.currentTimeMillis();
        Process process = builder.start();
        process.waitFor();
        final long endTime = System.currentTimeMillis();

        int exitValue = process.exitValue();
        InputStream inputStream = exitValue == 0 ? process.getInputStream() : process.getErrorStream();
        String consoleOutput = readStream(inputStream);
        return new ExecutionResult(exitValue, consoleOutput, (endTime - startTime));
    } catch (IOException | InterruptedException ex) {
        throw new CommandLineExecutorException(ex.getMessage());
    }
}

I'm not sure if this is the best way to control the time of execution of the sub process. For the memory I'm still looking for the best option.

I used to use a script to control memory and time with linux commands when i was using php but I want to know if there is a better way to achive this in java.

Upvotes: 1

Views: 1149

Answers (1)

Eugene Kuleshov
Eugene Kuleshov

Reputation: 31795

For monitoring child Java process you van use Java JMX to query various parameters of JVM process. See this answer for an example how to connect to remote JVM and this one for retrieving memory info.

For monitoring non-Java processes you can use SIGAR multiplatform API.

Upvotes: 1

Related Questions