What is a Callable in Java, and what are the differences between Callable and Runnable?

What is Callable?
Callable is an interface in Java found in the java.util.concurrent package. It is often used in multi-threading environments. Callable defines a single method, call(), which returns a value that can be obtained through Future<V> objects.
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class MyCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
// Perform your tasks here and return the result
return 42;
}
public static void main(String[] args) throws Exception {
Callable<Integer> callable = new MyCallable();
FutureTask<Integer> futureTask = new FutureTask<>(callable);
Thread thread = new Thread(futureTask);
thread.start();
Integer result = futureTask.get();
System.out.println("Result: " + result);
}
}Output :
Result: 42What is Runnable?
Runnable is an older interface in Java and is often used in single-threaded applications. Runnable defines a single method, run(), which sequentially performs tasks.
public class MyRunnable implements Runnable {
@Override
public void run() {
// Perform your tasks here
System.out.println("Hello, Runnable!");
}
public static void main(String[] args) {
Runnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
}Differences between Callable and Runnable
- The
call()method ofCallablecan return a value, while therun()method ofRunnablecannot return a value. - When working with
Callable, you can use mechanisms likeFutureorFutureTaskto obtain the result when the task is completed.Runnabledoes not provide such a mechanism directly. Callablecan specify checked exceptions (e.g.,Exception) when throwing exceptions, whileRunnablecannot throw checked exceptions.Callablereturns a result when the thread's work is completed, whileRunnableonly completes the work, requiring a separate mechanism to transmit the result.
The choice between which interface to use depends on the requirements of your project and the use of multi-threading. If you need to return a result or handle exceptions, Callable may be more appropriate. If you simply want to run a task in parallel, Runnable can be used.
