Ravi
Ravi

Reputation: 31417

When should prefer Callable over Runnable and why?

On SO, I found all theoretical difference between Callable and Runnable and all are almost similar. But, I didn't understand why was Callable introduced in later version ? What was the gap/flaws in Runnable, which Callable is capable of doing ? Anyone can explain with scenario where Callable is only solution ?

Upvotes: 3

Views: 1747

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533560

Callable has two differences. It can return a value or throw a checked exception.

This make a difference when using lambdas so that even though you don't specify which one to sue the compiler has to work it out.

// the lambda here must be a Callable as it returns an Integer
int result = executor.submit(() -> return 2);

// the lambda here must be a Runnable as it returns nothing
executors.submit(() -> System.out.println("Hello World"));

// the lambda here must be a Callable as an exception could be thrown
executor.submit(() -> {
   try (FileWriter out = new FileWriter("out.txt")) {
      out.write("Hello World\n");
   }
   return null; // Callable has to return something
});

Upvotes: 3

Florian Schaetz
Florian Schaetz

Reputation: 10652

Well, the documentation does answer a big part of your question:

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.

So, you are jusing Callable instead of Runnable, if...

  1. You need to throw a checked exception or...
  2. You need to return an object (of course you could simulate this by giving your runnable an internal result object, etc. - but it's easier that way)

For example...

ExecutorService service = ... some ExecutorService...;
Callable<Integer> myCallable = new MyCallable( ... some parameters ... );
Future<Integer> future = service.submit( myCallable );
...
Integer myResult = future.get(); // will wait and return return value from callable as soon as done

Upvotes: 0

Related Questions