We can no longer use the Runnable interface to do this. We must use the callable interface that was implemented in version 1.5 of java.
Example :
public class MyTask implements Callable<String> { @Override public String call() throws Exception { // Here your implementation return new String("Result"); } }
The Callable interface solves two problems: the thread can return something, defined by the generic parameter <String>, and the method call throws a Exception to not need the try-catch.
The tasks need to be performed by Callable ExecutorService, ie through the thread pool. The Thread class can not get a Callable:
ExecutorService executor = Executors.newCachedThreadPool(); executor.submit(new MyTask());
The question still is: where does the return Callable? The answer is in the submit method ExecutorService.
Understanding the return type Future
If we are using a Runnable we should use the execute method of ExecutorService, but when we use a Callable we should use the submit method. The difference is that the submit has a return, it is the Future type.
The submit method does not block the execution and can submit as many tasks we want.
public void test() throws Exception{ ExecutorService executor = Executors.newCachedThreadPool(); Future<String> futureCall = executor.submit(new MyTask()); String result = futureCall.get(); // Here the thread will be blocked // until the result came back. }
How to limit the thread response time?
String result = futureCall.get(10,TimeUnit.SECONDS); // Will waiting for ten seconds the result.
How to cancel the response time and unlock the thread?
futureCall.cancel(true);
Conclusions and Review
- To set a task of a thread use the Callable interface; .
- A Callable can return something and throw any exception;
- We must submit Callable through a ExecutorService;
- The submit method returns a Future ExecutorService;
- The Future will receive the return of a Callable Implementation Class;