Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 417
Ravi Avatar asked Sep 02 '25 04:09

Ravi


1 Answers

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
});
like image 68
Peter Lawrey Avatar answered Sep 04 '25 20:09

Peter Lawrey