Sobes.tech
Middle

What is the difference between the Runnable and Callable interfaces in Java?

sobes.tech AI

Answer from AI

The main difference is that Runnable cannot return a result and cannot throw a checked exception, whereas Callable can.

Runnable

  • Method run(): void run();
  • Does not return a value.
  • Cannot throw a checked exception (those inheriting from Exception, except RuntimeException).
  • Suitable for tasks that are simply executed without returning a result.

Callable

  • Method call(): V call() throws Exception; (where V is the return type).
  • Returns a value (type specified in <V>).
  • Can throw a checked exception.
  • Often used with ExecutorService and Future for asynchronous task execution and retrieving their results.

Usage in ExecutorService:

  • Runnable is passed to execute(Runnable task) or submit(Runnable task). The submit method returns a Future<?>.
  • Callable is passed to submit(Callable<T> task). The submit method returns a Future<T>.

Example of Runnable:

// Example Runnable
public class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("Runnable task running...");
    }
}

Example of Callable:

// Example Callable
import java.util.concurrent.Callable;

public class MyCallable implements Callable<String> {
    @Override
    public String call() throws Exception {
        System.out.println("Callable task running...");
        return "Task completed";
    }
}