Useful Tips : How to create a thread that must get a result with a timeout time

Many times threads are really useful to use, but most of the time you don’t want an asynchronous thread to run forever… Especially when you want it to execute tasks or fetch some data from a servlet…
It’s not always easy to think about how to do it, i once used another Timer thread to wake up this one, and it’s what one should do for regular tasks and/or real time systems, but for a one time task here’s the best solution i’ve ever used :


Callable<Integer> call = new Callable<Integer>() {
public Integer call() throws Exception {
// let's say you have here some task that will return an Integer value
Integer result = ...;
return result;
}
};

ExecutorService service = Executors.newSingleThreadExecutor();
try {
Future<Integer> ft = service.submit(call);
try {

// the concept of future Integer will allow you to get it using a timeout
// here we precise that the task must take less than 3 minutes :
int exitVal = ft.get(180, TimeUnit.SECONDS);
return exitVal;

} catch (TimeoutException to) {

System.err.println("The server took too long to answer, timeout reached !");

}

} finally {
service.shutdown();
}


Therefor, to sum up, you must encapsulate your task in a Callable object, and execute it using the Executors class. It’s the simplest way, and you don’t deal with the whole lifecycle of the working Thread.
Enjoy.

P.S. correcting the code because the executor service must be shutdown after use