Sunday, 5 April 2015

Please find below the use of java executor and Future task. This example also shows how to handle customed timed out operation. Please watch this tutorial in youtube. link: https://youtu.be/Zd4ckkD7K5E

package test;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class TimeoutImpl {

private String mymethod() {
return "Time out situation";

}

public static void main(String[] args) {

ExecutorService service = Executors.newSingleThreadScheduledExecutor();
Future future = null;

Callable callable = new Callable() {

public Object call() throws Exception {
Thread.sleep(1100);
return new TimeoutImpl().mymethod();
}
};


future = service.submit(callable);

try {
System.out.println(future.get(1, TimeUnit.SECONDS));
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
System.out.println("timeout occured");
e.printStackTrace();
}finally{
service.shutdown();
}

}

}