Sobes.tech
Junior — Middle

Explain the differences between the Callable and Runnable interfaces in Java and when it is preferable to use each.

sobes.tech AI

Answer from AI

The Runnable and Callable interfaces in Java are used to define tasks that can be executed in separate threads, but they have key differences:

  • Runnable:

    • The run() method does not return a result and cannot throw checked exceptions.
    • Used when the task does not require a return 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 or handle exceptions.
    • Usually used with ExecutorService and Future to get the result asynchronously.
    • Example:
      Callable<Integer> task = () -> {
          // Some computational logic
          return 42;
      };
      ExecutorService executor = Executors.newSingleThreadExecutor();
      Future<Integer> future = executor.submit(task);
      Integer result = future.get();
      executor.shutdown();
      

When to use:

  • For simple tasks without a result — Runnable.
  • When a result or exception handling is needed — Callable.
Explain the differences between the Callable and… - sobes.tech