title: How to successfully destroy the process if it takes too much time in Java?
body: <p>I am executing a shell script from my Java program using <code>Process</code> and I want to kill/destroy that process if my script takes long time. What is the best way to do this?</p>
  
  <p>Below is my code:</p>
  
  <pre><code>public static void main(String[] args) throws IOException, InterruptedException {
  
      // Your script
      String script = "#!/bin/bash\n\necho \"Hello World\"\n\n readonly PARAM1=$param1\n echo $PARAM1\n\nreadonly PARAM2=$param2\n echo $PARAM2\n\n";
  
      // create a temp file and write your script to it
      File tempScript = File.createTempFile("temp_scripts_", "");
      tempScript.setExecutable(true);
      try (OutputStream output = new FileOutputStream(tempScript)) {
          output.write(script.getBytes());
      }
  
      // build the process object and start it
      List&lt;String&gt; commandList = new ArrayList&lt;&gt;();
      commandList.add(tempScript.getAbsolutePath());
      ProcessBuilder builder = new ProcessBuilder(commandList);
      builder.redirectErrorStream(true);
      builder.environment().put("param1", "abc");
      builder.environment().put("param2", "xyz");
      Process shell = builder.start();
  
      // read the output and show it
      try (BufferedReader reader = new BufferedReader(new InputStreamReader(shell.getInputStream()))) {
          String line;
          while ((line = reader.readLine()) != null) {
              System.out.println(line);
          }
      }
  
      // wait for the process to finish
      // but I want to kill/destroy the process if it takes too much time
      int exitCode = shell.waitFor();
  
      // delete your temp file
      tempScript.delete();
  
      // check the exit code (exit code = 0 usually means "executed ok")
      System.out.println("EXIT CODE: " + exitCode);
  }
  </code></pre>