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?

in the "write once, run anywhere" cross-platform sense, no. But making a tiny piece of non-portable code that will work on every Un*x (including OS X) and every Windows machine really ain't that hard. +1 to Stephen C's answer.
–
SyntaxT3rr0rMay 19 '10 at 15:03

2 Answers
2

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.)

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.)