Employing Future and Callable for result-bearing task execution
In Java, Future and Callable are used together to execute tasks asynchronously and obtain results at a later point in time:
- Callable interface: A functional interface that represents a task capable of producing a result:
call()
: This method encapsulates the task’s logic and returns the result
- Future interface: This represents the eventual completion (or failure) of a Callable task and its associated result:
get()
: This method retrieves the result, blocking if necessary until completionisDone()
: This method checks whether the task is finished- Submitting tasks:
ExecutorService
accepts Callables, returning Futures for tracking completion and results
Here is an example of Callable and Future interfaces:
ExecutorService executor = Executors.newFixedThreadPool(2); Callable<Integer> task = () -> { // perform some computation return 42; }; Future...