Sobes.tech
Junior — Middle

What is the main purpose of using the Callable interface in programming?

sobes.tech AI

Answer from AI

The Callable interface in Java is used to define tasks that can be executed in a separate thread and return a result. Unlike Runnable, which does not return a value and cannot throw checked exceptions, Callable:

  • Returns a result via the call() method.
  • Can throw exceptions.

This allows using Callable with ExecutorService for asynchronous task execution and obtaining the result through Future.

Example:

Callable<Integer> task = () -> {
    // Some computational task
    return 123;
};
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(task);
Integer result = future.get(); // Get the result
executor.shutdown();
What is the main purpose of using the Callable… - sobes.tech