Thursday 8 December 2011

Execute thread from Java with timeout

In order to execute java thread with timeout, please use following snippet:

    private void executeThreadWithTimeout() {
     try {
      int timeout = 180;
      ExecutorService executor = Executors.newSingleThreadExecutor();
            executor.invokeAll(Arrays.asList(new Task()), timeout, TimeUnit.SECONDS);
            executor.shutdown();
     } catch (Exception e) {
     }
    }
    
    private class Task implements Callable {
        public Integer call() throws Exception {
            try {
             // Task go here
             Thread.sleep(60 * 60 * 1000);
            } catch (Exception e) {
            }
            return 0;
        }
    }
  

Wednesday 7 December 2011

Execute command line process from Java with timeout

In order to execute command line process from Java with timeout, please use following snippet:

 public static void executeCommand(String command, long timeoutInSeconds) throws Exception {
  ExecutorService service = Executors.newSingleThreadExecutor();
  Process process = Runtime.getRuntime().exec(command);
  try {
   Callable call = new CallableProcess(process);
   Future future = service.submit(call);
   int exitValue = future.get(timeoutInSeconds, TimeUnit.SECONDS);
   if (exitValue != 0) {
    throw new Exception("Process did not exit correctly");
   }
  } catch (ExecutionException e) {
   throw new Exception("Process failed to execute", e);
  } catch (TimeoutException e) {
   process.destroy();
   throw new Exception("Process timed out", e);
  } finally {
   service.shutdown();
  }
 }
 
 private static class CallableProcess implements Callable {
 
  private Process p;
 
  public CallableProcess(Process process) {
   p = process;
  }
 
  public Integer call() throws Exception {
   return p.waitFor();
  }
 }