Reputation: 1095
I understand that callable's call can throw the exception to the parent method calling it which is not the case with runnable.
I wonder how because it's a thread method and is the bottommost method of the thread stack.
Upvotes: 18
Views: 15636
Reputation: 382464
The point of Callable
is to have your exception thrown to your calling thread, for example when you get the result of a Future
to which you submitted your callable
.
public class CallableClass implements Callable<String> {
...
}
ExecutorService executor = new ScheduledThreadPoolExecutor(5);
Future<Integer> future = executor.submit(callable);
try {
System.out.println(future.get());
} catch (Exception e) {
// do something
}
Upvotes: 18
Reputation: 3973
Callable.call()
can't be the bottommost stack frame. It's always called by another method that will then catch the exception. Callable
should usually be used to asynchronously compute values and later get them with a Future
object. The operation might throw an exception that is later rethrown when you try to get the Future
's value.
Runnable
is simply supposed to run an operation that doesn't return anything. All exception handling should be done within the Runnable
because it's unclear how any exceptions thrown in Runnable.run()
should be handled. (The exception from a Callable
is usually returned to the caller with the Future
)
Upvotes: 6