Sobes.tech
Junior — Middle

What is the purpose of the Callable interface in programming?

sobes.tech AI

Answer from AI

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

  • Returning a result via the call() method.
  • Throwing checked exceptions.

This is especially useful when working with thread pools and the ExecutorService class, where you can obtain a Future object to track the result of an asynchronous task.

Example of usage:

import java.util.concurrent.Callable;

public class SumTask implements Callable<Integer> {
    private int a, b;

    public SumTask(int a, int b) {
        this.a = a;
        this.b = b;
    }

    @Override
    public Integer call() {
        return a + b;
    }
}

Then, this task can be submitted to an ExecutorService and the result obtained via Future."}]}]}

What is the purpose of the Callable interface in… - sobes.tech