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;
        }
    }
  

No comments:

Post a Comment