Friday, May 17, 2013

What is difference between Callable and Runnable Interface ?

As per Java documentation 

"Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. A Runnable, however, does not return a result and cannot throw a checked exception."

public interface Callable { 
 V call() throws Exception; 
In order to convert Runnable to Callable use the following utility method provided by Executors class

Callable callable = Executors.callable(Runnable task);

Callable, however must be executed using a ExecutorService instead of Thread as shown below.

result = exec.submit(aCallable).get();

Submitting a callable to ExecutorService returns Future Object which represents the lifecycle of a task and provides methods to check if the task has been completed or cancelled, retrieve the results and cancel the task.

Here is the source for Future Interface

public interface Future { 
  boolean cancel(boolean mayInterruptIfRunning); 
  boolean isCancelled(); 
  boolean isDone(); 
  V get() throws InterruptedException, ExecutionException; 
  V get(long timeout, TimeUnit unit) 
  throws InterruptedException, ExecutionException, TimeoutException;

1 comment:

Your comment will be published after review from moderator