2

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?

Brad Mace
  • 27,194
  • 17
  • 102
  • 148
  • Related question: [Cross-platform way to change java process priority](http://stackoverflow.com/q/2865610/772981), no positive answer. – Jarekczek Oct 15 '12 at 07:20

6 Answers6

5

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.

Jarekczek
  • 7,456
  • 3
  • 46
  • 66
4

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

renice +5 `pgrep java`
edgester
  • 493
  • 4
  • 14
  • This assumes that [process nice-ness affects Java thread priority](http://stackoverflow.com/questions/43786492/does-nice-affect-the-priority-of-java-threads). – Raedwald May 08 '17 at 09:13
2

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

ionice -c 3 -n 7 -p PID
wojciechz
  • 1,086
  • 8
  • 16
2

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.

kervin
  • 11,672
  • 5
  • 42
  • 59
1

Use:

nice --adjustment=5 java whatever

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

Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134
0

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.

Chris Johnson
  • 2,631
  • 2
  • 18
  • 17