Friday, June 14, 2013

Ruannable vs Callable<T>


"The 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."

Runnable Callable<T>
Introduced in Java 1.0 Introduced in Java 1.5 as part of java.util.concurrent library
Runnable cannot be parametrized  Callable is a parametrized type whose type parameter indicates the return type of its run method
Classes implementing Runnable needs to implement run() method Classes implementing Callable needs to implement call() method
Runnable.run() returns no Value Callable.call() returns a value of Type T
Can not throw Checked Exceptions Can throw Checked Exceptions
public class RunnableTest implements Runnable {
              @Override
              public void run() {
                         //any processing
              }
}
import java.util.concurrent.Callable;


public class CallableTest implements Callable
          @Override 
           public String call() throws Exception { 
                      // any processing
                    return new String("I am Callable and can return value and throw checked exception"); 
              } 
}

3 comments:

Unknown said...

Callable can be used with Executors, where Runnable cannot be.

Basil.Bourque said...

@AkhilJain Incorrect, both Callable and Runnable work with Executors. See the java.util.concurrent.Executor method "execute" that takes a Runnable. See the Tutorial explain how an ExecutorService accepts Callable as well as Runnable.

Anonymous said...

Callable can be used with invokeAny and invokeAll method of ExecutorService but Runnablecan not.