4

I have a .sh script with many jar files in it. Each jar file has unique launch arguments. I must limit all the jar files to not use more than %5 CPU each.

nohup java -a dsasda -p adss
nohup java -a dsasad -p adds
nohup java -a dsdasa -p adsa
nohup java -a dsdsa -p adds
nohup java -a ddassa -p adas

I've been reading about the cpulimit tool, how do I use it to target individual jars?

5
+50

Using cpulimit

I'll lead with the tool you proposed; cpulimit can definitely do what you want. nohup cpulimit --background --limit=5 -- java -a dsasda -p adss

Bear in mind that 5% is 5% of a single CPU core, not of the machine's total computing power. Scale that up if you wanted to use 5% of a multi-core machine.

You probably will want to also pass the --quiet argument to cpulimit.

If your desire isn't to specifically limit the process to 5%, but just to keep java from bogging down your machine, consider instead using nice.

Using nice

nice will lower the priority of your java processes so that they won't hog all of the CPU time & slow things down. Unlike cpulimit, nice will let the java processes use more than 5% of the CPU if nothing else wants to use it.

nohup nice java -a dsasda -p adss

nice accepts one optional argument, --adjustment=N where N is an integer ranging from 19 (very low priority) to 0 (normal) or even to -20 (very high priority, but only available if you're root). It'll default to 10 which is probably fine.

  • I am working with jar files that could have potential memory leaks. CPU priorities do not go well with leaked things. Doesn't matter if its low priority, it will still use up all spare cpu, making the machine lag. – Web Master Aug 27 '16 at 22:44
  • Voted up because its a better answer than mine! – Nick Sillito Aug 28 '16 at 8:01
3

You can use cpulimit as you suggest, you target the limit by specifying the PID of the process that you want to limit, so you could spawn and limit each of the above tasks to 5% of the CPU with the following script:

#!/bin/sh
nohup java -a dsasda -p adss &
nohup cpulimit -p $! -l 5 >/dev/null &
nohup java -a dsasad -p adds &
nohup cpulimit -p $! -l 5 >/dev/null &
nohup java -a dsdasa -p adsa &
nohup cpulimit -p $! -l 5 >/dev/null &
nohup java -a dsdsa -p adds &
nohup cpulimit -p $! -l 5 >/dev/null &
nohup java -a ddassa -p adas &
nohup cpulimit -p $! -l 5 >/dev/null &

Note that $! means the PID of the last process spawned by the shell (in this case the java command in the previous line). The -l 5 means limit to 5%.

  • 1
    $! is not the last process spawned by the shell, it's the PID of the last backgrounded process.. – heemayl Aug 25 '16 at 17:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.