1

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.

1 Answer 1

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.