What is the difference between Callable and Runnable?

Callable and Runnable are both interfaces used to execute tasks in a separate thread, but they serve different purposes. Runnable is suitable for tasks that do not need to return a value, whereas Callable is designed for tasks that need to produce a result or may throw checked exceptions. Callable works with Future objects, allowing the caller to retrieve the result after task completion.

Key Points:

• Runnable's run() method does not return any value, while Callable's call() method returns a result. • Runnable cannot throw checked exceptions directly, whereas Callable can throw checked exceptions. • Callable is commonly used with ExecutorService and Future to obtain asynchronous results. • Runnable is simpler and suitable for fire-and-forget tasks. • Callable is preferred when background processing needs to return data or status information.

Example:

Suppose you want to send an email notification in the background without expecting any response. Runnable is sufficient. However, if you need to calculate a report and return the generated result, Callable is the better choice.

Code Example:

import java.util.concurrent.*;

public class CallableVsRunnable {

    public static void main(String[] args) throws Exception {

        ExecutorService executor = Executors.newFixedThreadPool(1);

        Callable<String> callableTask = () -> {
            return "Task Completed Successfully";
        };

        Future<String> future = executor.submit(callableTask);

        System.out.println(future.get());

        executor.shutdown();
    }
}

Interview Tip:

A concise interview answer is: "Runnable is used for tasks that do not return a result and cannot throw checked exceptions, whereas Callable can return a value, throw checked exceptions, and is typically executed through ExecutorService with a Future object."