8 Replies Latest reply: Jun 12, 2012 4:17 AM by rukbat RSS

    Finding hard and soft open file limits from within jvm in linux

      Hi All,

      I have a problem where I need to find out the hard and soft open file limits for the process in linux from within a java program. When I execute ulimit from the terminal it gives separate values for hard and soft open file limits.

      From shell if I run the command then the output is given below:

      $ ulimit -n
      $ ulimit -Hn

      The java program is given below:

      import java.io.BufferedReader;
      import java.io.IOException;
      import java.io.InputStream;
      import java.io.InputStreamReader;
      import java.io.Reader;
      import java.io.StringWriter;
      import java.io.Writer;

      public class LinuxInteractor {
      public static int executeCommand(String command, boolean waitForResponse, OutputHandler handler) {
      int shellExitStatus = -1;
      ProcessBuilder pb = new ProcessBuilder("bash", "-c", command);
      try {
      Process shell = pb.start();

      if (waitForResponse) {

      // To capture output from the shell
      InputStream shellIn = shell.getInputStream();

      // Wait for the shell to finish and get the return code
      shellExitStatus = shell.waitFor();

      convertStreamToStr(shellIn, handler);

      catch (IOException e) {
      .println("Error occured while executing Linux command. Error Description: "
      + e.getMessage());
      catch (InterruptedException e) {
      .println("Error occured while executing Linux command. Error Description: "
      + e.getMessage());
      return shellExitStatus;

      public static String convertStreamToStr(InputStream is, OutputHandler handler) throws IOException {

      if (is != null) {
      Writer writer = new StringWriter();

      char[] buffer = new char[1024];
      try {
      Reader reader = new BufferedReader(new InputStreamReader(is,
      int n;
      while ((n = reader.read(buffer)) != -1) {
      String output = new String(buffer, 0, n);
      writer.write(buffer, 0, n);

      if(handler != null)
      } finally {
      return writer.toString();
      } else {
      return "";

      public abstract static class OutputHandler {
      public abstract void execute(String str);

      public static void main(String[] args) {
      OutputHandler handler = new OutputHandler() {
      public void execute(String str) {

      System.out.print("ulimit -n : ");
      LinuxInteractor.executeCommand("ulimit -n", true, handler);
      System.out.print("ulimit -Hn : ");
      LinuxInteractor.executeCommand("ulimit -Hn", true, handler);

      If I run this program the output is given below:

      $ java LinuxInteractor
      ulimit -n : 4096

      ulimit -Hn : 4096

      I have used ubuntu 12.04, Groovy Version: 1.8.4 JVM: 1.6.0_29 for this execution.

      Please help me in understanding this behavior and how do I get a correct result from withing the java program.