Video in progress
What is the difference between the Runnable and Callable interfaces?
Runnable.run() returns nothing and can't throw a checked exception. Callable.call() returns a result and may throw Exception. It is usually used with ExecutorService.submit().
📖 Answer
Runnable r = () -> log.info("faqat ish qiladi");
Callable<BigDecimal> c = () -> {
// you can freely throw a checked exception here
return rateClient.fetchRate("USD");
};
Future<BigDecimal> f = executor.submit(c);
BigDecimal rate = f.get();
If an exception is thrown inside a Callable, it doesn't disappear: f.get() wraps it in an ExecutionException, and the original cause is in getCause().
The historical reason: Runnable has existed since Java 1.0, while Callable was added in Java 5 along with java.util.concurrent.
new Thread(...) accepts only a Runnable. If you want to run a Callable on a thread, you have to wrap it in a FutureTask, but in practice using an executor is simpler.
Sign up to mark studied questions and save your progress.