Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross-platform way to change java process priority

Tags:

java

I need to invoke .jar file in separate JVM from another java application, and it very CPU-consuming, so it should run with background priority in order not to affect the rest of the system. Is there any cross-platform method to do this?

like image 408
gordon-quad Avatar asked May 19 '10 12:05

gordon-quad


People also ask

How do I reduce process priority?

You can change the scheduling priority of a running process to a value lower or higher than the base scheduling priority by using the renice command from the command line. This command changes the nice value of a process.


2 Answers

The simple answer is that there is no portable way to change the priority of a Process in Java. (Threads - yes, Processes - no.)

If your Java application needs to start a new JVM to run the CPU intensive application, then the chances are that it is already not entirely portable. For example, you will typically need to give the pathname of the java command (or equivalent), a -cp argument (or equivalent), system specific JVM options, and so on.

So, assuming that the command to launch the JVM is already non-portable, it should hardly matter if you replace the command with a wrapper script that does OS-specific things to change the priority of the launched process. (For example, for UNIX or Linux you could simply use nice to launch the JVM.)

like image 115
Stephen C Avatar answered Nov 10 '22 21:11

Stephen C


I don't know the way to set the priority for an external process. Thread however has a setPriority method, so if you control the target application, you could perhaps add a switch, telling the application to set its own priority to minimum:

theThread.setPriority(Thread.MIN_PRIORITY);

If it still affects the system, I suggest you interleave some short sleeping to offload the cpu.


Another option:

If you put the target .jar in the classpath of the "initiating" application, you can simply invoke the main-method of the jar-file in a newly created thread, and then set the priority using the above method. (This should work even if you don't control the source-code of the target jar file.)

like image 38
aioobe Avatar answered Nov 10 '22 19:11

aioobe