Setting a good value for a Java program running on Linux

I want my Java program to lower priority so that it does not overwhelm the system. My initial thought was to use Thread.currentThread().setPriority(5) , but this is apparently just its priority in the JVM.

Then I thought that maybe I will bow and call the system command, but Thread.getId() also just a JVM identifier, so I don’t even know which process identifier should go to renice .

Is there a way for a Java program to do something like this?

+1
source share
6 answers

If your program is the only working Java program, you can run

 renice +5 `pgrep java` 
+4
source

Since we have to make this platform-dependent, I start the shell process from java and restore its parent. The parent process is our Java process.

 import java.io.*; public class Pid { public static void main(String sArgs[]) throws java.io.IOException, InterruptedException { Process p = Runtime.getRuntime().exec( new String[] { "sh", "-c", "renice 8 `ps h -o ppid $$`" // or: "renice 8 `cat /proc/$$/stat|awk '{print $4}'`" } ); // we're done here, the remaining code is for debugging purposes only p.waitFor(); BufferedReader bre = new BufferedReader(new InputStreamReader( p.getErrorStream())); System.out.println(bre.readLine()); BufferedReader bro = new BufferedReader(new InputStreamReader( p.getInputStream())); System.out.println(bro.readLine()); Thread.sleep(10000); } } 

By the way: are you Brad Mays from jEdit? Nice to meet you.

+3
source

In addition to renice - you can also use ionice comand. For example:

 ionice -c 3 -n 7 -p PID 
+2
source

See also https://github.com/jnr/jnr-posix/ .

This POSIX library should allow you to get some of the Linux Posix Nice features, such as ...

https://github.com/jnr/jnr-posix/blob/master/src/main/java/jnr/posix/LibC.java for OS level setPriority (), i.e. setpriority (2)

jnr-posix is ​​also located in Maven.

+2
source

Using:

 nice --adjustment=5 java whatever 

to launch your Java program and assign priority in just one step.

+1
source

My suggestion is to call your java application from a bash script or script start / stop service, then find the process id after start and change it.

0
source

All Articles