Java Callable interface uses Generic to define the return type of Object. Executors class provide useful methods to execute Java Callable in a thread pool. Since callable tasks run in parallel, we have to wait for the returned Object.
Java Callable tasks return java.util.concurrent.Future object. Using Java Future object, we can find out the status of the Callable task and get the returned Object. It provides get() method that can wait for the Callable to finish and then return the result.
Java Future provides cancel() method to cancel the associated Callable task. There is an overloaded version of get() method where we can specify the time to wait for the result, it’s useful to avoid current thread getting blocked for a longer time. There are isDone() and isCancelled() methods to find out the current status of the associated Callable task.
A simple example of Java Callable task that returns the name of the thread executing the task after one second. We are using the Executor framework to execute 20 tasks in parallel and use Java Future to get the result of the submitted tasks.
Once we execute the above program, we can notice the delay in output because of java Future get() method waits for the java callable task to complete. Also, notice that there are only 5 threads executing these tasks.
Here is the snippet of the output of the above program.
What if we want to override some of the methods of Java Future interface, for example overriding get() method to timeout after some default time rather than waiting indefinitely, in this case, Java FutureTask class comes handy that is the base implementation of Future interface. Check out Java FutureTask Example to learn more about this class.