code: public static String pidMemoryUsage(int pid) throws IOException {
      Process process =
          new ProcessBuilder().command("ps", "-o", "pid,rss,vsz", "-p", Long.toString(pid)).start();
  
      BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
  
      reader.readLine(); // Skip header
  
      String line = reader.readLine();
      String[] parts = line.trim().split("\\s+", 3);
  
      int readPid = Integer.parseInt(parts[0]);
      if (pid != readPid) {
        throw new RuntimeException("`ps` returned something unexpected: '" + line + "'");
      }
  
      long rss = Long.parseLong(parts[1]) * 1024;
      long vsz = Long.parseLong(parts[2]);
  
      // 0 pid, 1 rss, 2 vsz
      return String.format("%d\t%d", rss, vsz);
    }
docs: Calculates the memory usage according to ps for a given pid.
  
  @param pid the pid of the process
  @return the pid, rss, and vsz for the process
  @throws IOException if executing ps fails