Callable<V> interface represents a task that can return a result upon its execution.
The type parameter V is type of the result of the task.
call() method from Callable interface can return a value of any type and can throw an exception.
It is declared as follows:
public interface Callable<V> { V call() throws Exception; }
The following code shows how to use the Callable interface to create a task.
It uses a Callable Task with an Executor.
call() method contains the logic for task.
ExecutorService.submit() method returns a Future object.
Future interface tracks the progress of the task that you submit.
import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.ExecutionException; class MyTask implements Callable<Integer> { private int taskId; private int loopCounter; public MyTask(int taskId, int loopCounter) { this.taskId = taskId; this.loopCounter = loopCounter; }/* w w w . j a v a 2 s. co m*/ public Integer call() throws InterruptedException { int totalSleepTime = 0; for (int i = 1; i <= loopCounter; i++) { try { int sleepTime = 3; System.out.println("Task #" + this.taskId + " - Iteration #" + i + " is going to sleep for " + sleepTime + " seconds."); Thread.sleep(sleepTime * 1000); totalSleepTime = totalSleepTime + sleepTime; } catch (Exception e) { System.out.println("Task #" + this.taskId + " has been interupted."); throw e; } } return totalSleepTime; } } public class Main { public static void main(String[] args) { ExecutorService exec = Executors.newFixedThreadPool(3); MyTask task = new MyTask(1, 3); Future<Integer> submittedTask = exec.submit(task); try { Integer result = submittedTask.get(); System.out.println("Task's total sleep time: " + result + " seconds"); } catch (ExecutionException e) { System.out.println("Error in executing the task."); } catch (InterruptedException e) { System.out.println("Task execution has been interrupted."); } exec.shutdown(); } }