Sobes.tech
Junior — Middle

What are the differences between the Runnable and Callable interfaces in Java?

sobes.tech AI

Answer from AI

The Runnable and Callable interfaces in Java are used for executing tasks in separate threads but have key differences:

  • Runnable:

    • The run() method does not return a result and cannot throw checked exceptions.
    • Used when the task does not need to return a value.
    • Example:
      Runnable task = () -> System.out.println("Executing task");
      new Thread(task).start();
      
  • Callable<V>:

    • The call() method returns a result of type V and can throw exceptions.
    • Used when you need to obtain the result of the task execution.
    • Usually used with ExecutorService and Future.
    • Example:
      Callable<Integer> task = () -> {
          // computations
          return 123;
      };
      ExecutorService executor = Executors.newSingleThreadExecutor();
      Future<Integer> future = executor.submit(task);
      Integer result = future.get();
      executor.shutdown();
      

Thus, Callable extends the capabilities of Runnable by allowing to return a result and handle exceptions.