Setting nice value of Java program running on linux

偶尔善良 提交于 2019-12-11 01:12:30

问题


I want my Java program to lower it's priority some so it doesn't overwhelm the system. My initial thought was to use Thread.currentThread().setPriority(5) but that appears to be merely its priority within the JVM.

Then I thought maybe I'd cludge it and invoke a system command, but Thread.getId() is also merely the JVM's id, so I don't even know what process id to pass to renice.

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


回答1:


If your program is the only running java program, then you can run

renice +5 `pgrep java`



回答2:


Since we must do it in a platform dependent way, I run a shell process from java and it renices its parent. The parrent happens to be 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);
  }
}

BTW: are you Brad Mace from jEdit? Nice to meet you.




回答3:


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

ionice -c 3 -n 7 -p PID



回答4:


Also look at https://github.com/jnr/jnr-posix/.

This POSIX library should allow you to get at some of the Linux Posix Nice functions like...

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

jnr-posix is also in Maven.




回答5:


Use:

nice --adjustment=5 java whatever

to run your java program and assign the priority in just one step.




回答6:


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



来源:https://stackoverflow.com/questions/12065142/setting-nice-value-of-java-program-running-on-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!