Tuesday, March 30, 2021

Java Callable Future

java.util.concurrent.Callable interface similar to Runnable interface to execute a task in multithreaded environment. Callable interface can return any result of type  java.util.concurrent.Future object after completion of a task.  Callable has single call() method similar to run() method of Runnable but has capability to return result.

Future provides get() method to fetch the result of Callable task, its a blocking method, will wait until task completes its execution and return result. Also provides overloaded version of get() method to define the timeout for the task to avoid infinite wait for task to complete.

Also provides cancel() method to cancel the task.

isDone() & isCancelled() provides current status of tasks.


public class Test13 {

public static void main(String args[]) throws InterruptedException, ExecutionException {

List<Future<String>> list = new ArrayList<>();

ExecutorService executor  = Executors.newFixedThreadPool(5);

for(int i=0; i<20; i++) {

Future<String> response=executor.submit(new Test12());

list.add(response);

}

for (Future<String> value : list) {

System.out.println(value.get()+"Thread Name ->"+ Thread.currentThread().getName());

}

executor.shutdown();

}

}


public class Test12 implements Callable<String> {

@Override

public String call() throws Exception {

return "success";

}

}



Labels: , , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home