Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start a Java process at low priority using Runtime.exec / ProcessBuilder.start?

I'm trying to start an external process via Java using the ProcessBuilder class, and that much works. Currently running using the command:

new ProcessBuilder("java", "-jar", jarfile, args);

What I would like to do is just this, but to start the process with low priority. My program is currently only running on Windows, so a window-specific solution is fine by me. Some research suggests I use the "start" command, but when I try doing this from Java it gives an exception saying it is an unrecognized command (the same command works from cmd.exe).

Does anyone know how to launch a process from Java (Windows-specific if need be), with belownormal priority?

like image 280
Andrew Avatar asked Jun 03 '11 06:06

Andrew


People also ask

What is ProcessBuilder in Java?

This class is used to create operating system processes. Each ProcessBuilder instance manages a collection of process attributes. The start() method creates a new Process instance with those attributes.

Is ProcessBuilder thread safe?

The ProcessBuilder Class Note that ProcessBuilder is not a synchronized class; hence, if it is not synchronized explicitly, it not thread safe to access the instance of this class through multiple threads.


1 Answers

Use start command. It is windows dependent but does what you need. I have read there is no cross platform way for this.

ProcessBuilder pb = new ProcessBuilder("cmd", "/C start /B /belownormal javaws -version");
System.out.println("Before start");
Process start = pb.start();

It is even possible to read Input end Error streams.

To wait:

ProcessBuilder pb = new ProcessBuilder("cmd", "/C start /B /belownormal /WAIT javaws -sdasd");
System.out.println("Before start");
Process start = pb.start();
start.waitFor();
System.out.println("Done");

For premature destroy:

ProcessBuilder pb = new ProcessBuilder("cmd", "/C start /B /belownormal /WAIT javaws -sdasd");
System.out.println("Before start");
Process start = pb.start();
start.destroy();
start.waitFor();

System.out.println("Done");
like image 56
teodozjan Avatar answered Oct 01 '22 11:10

teodozjan