Java Callable and futures in Multi Threading Environment


pre code { background-color: #eee; border: 1px solid #999; display: block; padding: 20px; }
Runnable Interface has run() method we use does not take any argument and also we can not return any value from it.

The Callable Interface has call() method that takes and returns a generic value. The return value can be captured in a Future object, also Callables call() Method throws Checked exception, so you can propagate down through the running hierarchy.


Executor Interface works with both runnable() and callable(). So if you need to return something then you use callable() else runnable().

To do this we can use Executor.execute and pass runnable(Executor.execute(runnable), instead of Thread.start.

Below is an example of java Callable  with Future.


package com.app.tests;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.app.runnables.LoggingProcessor;

public class TestOtherAPi {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		ExecutorService service = Executors.newFixedThreadPool(3);
		List> callables = new ArrayList<>();
		callables.add(new LoggingProcessor());
		callables.add(new LoggingProcessor());
		callables.add(new LoggingProcessor());
	
	  List> futures;
	  
	try {
		futures = service.invokeAll(callables);
		  for (Future future : futures) {
			  System.out.println("Result is"+future.get());
		}
	} catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (ExecutionException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	try {
		service.invokeAny(callables);
	} catch (InterruptedException e) {
		// TODO Auto-generated catch block
		Logger.getLogger(TestOtherAPi.class.getName()).log(Level.SEVERE,null,e);
	} catch (ExecutionException e) {
		// TODO Auto-generated catch block
		Logger.getLogger(TestOtherAPi.class.getName()).log(Level.SEVERE,null,e);
	}
	  

	}

}




Previous
Next Post »

Pages