mursalin
mursalin

Reputation: 1181

Memory comsumption of a process initiated by Java ProcessBuilder

Is there a way to limit memory consumption of a process initiated by java processbuilder ? or to get the maximum memory used by the process?

I have tried using the following code..but is always returns 0.

ProcessBuilder p = new ProcessBuilder(command);
before=Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory();
Process pp = p.start();
after=Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory();
System.out.println("Used : "+before-after);

I am a beginner..please pardon if the question is silly...

Upvotes: 4

Views: 1961

Answers (2)

syntagma
syntagma

Reputation: 24354

No, the processes started using ProcessBuilder are operating system processes and there is no way to control the way to limit their resources from JVM/using Java APIs. You could however try to limit resources, after getting PID of the Process using operating system APIs (for example, cgroups on Linux).

Also, this:

after = Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory();

is not related to ProcessBuilder (apart from some allocation Java is making for ProcessBuilder object) the way you think. It returns memory of Java Runtime, not the process you have started using ProcessBuilder.

Upvotes: 4

davidxxx
davidxxx

Reputation: 131536

ProcessBuilder constructors provide a way to set arguments to the program.
For example you have :

public ProcessBuilder(String... command) 

where the command argument vargs contain the program but also its arguments if provided.

And you have also a constructor that provides the same goal but with a List as parameter :

public ProcessBuilder(List<String> command) 

In your case, if your program is a Java program, you could write something like that to limit to 512M the maximum memory used by the process :

ProcessBuilder processBuilder = 
        new ProcessBuilder(pathToTheJavaCommand, "-Xmx512m", "-cp", classpath, yourClass);

In the case of your program is not a Java program, either your program provides a parameter to set the max memory allocated for it or you shoud use a OS specific feature that limits the consumed memory. But the second case is not necessary fine as it may have critical side effects on the started program if the memory is absolutely required for the program.

At last, Runtime.getRuntime() returns the runtime object associated with the current Java application, not the runtime object of the last launched Process.

Upvotes: 2

Related Questions