Reputation: 3599
I am trying to set ulimit under which my java program runs. Currently, it seems that ulimit -n is set to 4096 because when I run this code (which is a part of my java program), it outputs 4096.
ProcessBuilder processBuilder = new ProcessBuilder("/bin/bash", "-c", "ulimit -n");
try {
Process process = processBuilder.start();
// Prints 4096.
LOGGER_.info(getStringFromInputStream(process.getInputStream()));
} catch (IOException e) {
// The flow does not reach this catch block.
LOGGER_.error("exception caught: " + e.getMessage());
}
Is it possible to change it to something else, say 8192? I tried this:
ProcessBuilder processBuilder2 = new ProcessBuilder("/bin/bash", "-c", "ulimit -n 8192");
try {
Process process = processBuilder2.start();
LOGGER_.error("starting agent2...");
LOGGER_.error(getStringFromInputStream(process.getInputStream()));
} catch (IOException e) {
LOGGER_.error("exception caught2: " + e.getMessage());
}
and
try {
String[] cmdString = new String[3];
cmdString[0] = "/bin/bash";
cmdString[1] = "-c";
cmdString[2] = "ulimit -n 8192";
Process process = Runtime.getRuntime().exec(cmdString);
LOGGER_.error(getStringFromInputStream(process.getInputStream()));
} catch (IOException e) {
LOGGER_.error("exception caught:" + e.getMessage());
}
But I am not sure if these are the correct way to do so. Also, if the ulimit -n is even getting modified or not.
Upvotes: 1
Views: 2617
Reputation: 3599
I did a workaround that works. I was using a shell script that executed the java program. So, I set the ulimit before the shell script executed the running-the-java part. As answered by @apangin, this set the ulimit of the shell process and the java process that spawned from this shell process, inherited this ulimit.
Upvotes: 0
Reputation: 98334
ulimit
command updates the limits of the current process and all inherited processes. When you invoke ulimit
using Runtime.exec
or ProcessBuilder
, it starts a new process and updates the limits of this new process with no effect on current Java process.
In order to apply new limits on itself, Java process should call setrlimit
function in its own context. Since there is no Java wrapper for this function, it can be called only via a native interface: JNI, JNA or JNR.
However, if Java runs under unprivileged user, updating file limit (ulimit -n
) is useless anyway, because HotSpot JVM updates this limit to maximum allowed value automatically - see this question.
Upvotes: 1