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. – SyntaxT3rr0r May 19 '10 at 15:03
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.)

- 698,415
- 94
- 811
- 1,216
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 sleep
ing 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.)

- 413,195
- 112
- 811
- 826
-
1I understand he needs to spawn another process, and this method is for a thread, so I don' think it can work... – Persimmonium May 19 '10 at 14:28
-
oh.. hmm.. good point. I suppose this only makes sense then, if there is a possibility to add a switch to the program being executed. – aioobe May 19 '10 at 14:40
-
If he has the source of the other process being run, it can set itself to MIN_PRIORITY, right? – Dean J May 19 '10 at 14:47
-
1@Dean J - that only affects the priority of a thread. Process priority is a different concept. – Stephen C May 19 '10 at 14:53