Multithreading - Callable

Many times we would like to have a facility by which we can have return values from the threads. Since the run() method of the Runnable interface has the return type void, it was not possible with that.

In the concurrency api, we have a new feature known as the Callable interface. This interface represents a thread that returns a value.

The Callable interface defines the single method call()

Object call() throws exception

The callable task is executed by calling the submit() method of the executor service.

Future submit(Callable c)

Future is an interface that holds the value returned by the thread. The value can be accessed using the get() method of the Future interface.

ExecutorService executorService = Executors.newFixedThreadPool(10);
List<ThreadToAddNumbers> list = new ArrayList<ThreadToAddNumbers>();for(int i=0; i< 100; i++) {
    list.add(new ThreadToAddNumbers(i, i*i));}

for(ThreadToAddNumbers threadToAddNumbers : list) {
    Future f = executorService.submit(threadToAddNumbers);    System.out.println("Result : " + f.get());}

An example for the callable and future interfaces can be found here

Comments

Popular posts from this blog

Collection Framework - HashSet And LinkedHashSet class

Collection Framework - Cursors in Java

Hashed data structures