java concurrency executing value returning tasks with callable and future

https://w‮tfigi.ww‬idea.com

In Java, the Callable interface provides a way to execute a task that returns a value and may throw an exception. The Future interface provides a way to retrieve the result of a Callable task and handle any exceptions that were thrown.

Here's an example of how to use Callable and Future to execute a value-returning task in Java:

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class CallableExample {
    public static void main(String[] args) {
        Callable<Integer> task = () -> {
            int sum = 0;
            for (int i = 1; i <= 10; i++) {
                sum += i;
            }
            return sum;
        };

        FutureTask<Integer> futureTask = new FutureTask<>(task);

        Thread thread = new Thread(futureTask);
        thread.start();

        try {
            int result = futureTask.get();
            System.out.println("Result: " + result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

In this example, we define a Callable task that calculates the sum of the numbers from 1 to 10. We create a FutureTask object with the Callable task as an argument. We then create a thread with the FutureTask object and start the thread.

We use the get() method of the FutureTask object to retrieve the result of the Callable task. The get() method blocks until the task has completed and returns the result. If an exception was thrown by the task, the get() method will re-throw the exception wrapped in an ExecutionException.

In this example, we catch InterruptedException and ExecutionException. InterruptedException is thrown if the thread is interrupted while waiting for the result. ExecutionException is thrown if the Callable task throws an exception.

Note that the get() method blocks until the task is complete. If you need to execute multiple tasks and retrieve their results asynchronously, you can use a thread pool and submit each task to the pool. The submit() method of the ExecutorService interface returns a Future object that you can use to retrieve the result of the task.