Execute thread from java with timeout
  This task use java to run thread. After period of time, if thread does not end normally, it is killed.
Execute thread using ExecutorService
  
    Create task class which implements Callable. Call executeThreadWithTimeout with instance of task class and timeout number.
    
private class Task implements Callable {
    public Integer call() throws Exception {
        try {
             // Task go here
        } catch (Exception e) {
        }
        return 0;
    }
}
private void executeThreadWithTimeout(Callable task, int timeout) {
    try {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.invokeAll(Arrays.asList(task), timeout, TimeUnit.SECONDS);
        executor.shutdown();
    } catch (Exception e) {
    }
}
    
   
 

 
No comments:
Post a Comment