java callable

www.igift‮moc.aedi‬

In Java, Callable is an interface in the java.util.concurrent package that defines a task that can be executed asynchronously and returns a result. It is similar to the Runnable interface, which defines a task that can be executed asynchronously but does not return a result.

The Callable interface defines a single method, call(), which takes no arguments and returns a value of the specified type. The call() method can throw a checked exception, which must be handled by the calling code.

To use a Callable object, you can submit it to an ExecutorService using the submit() method. The submit() method returns a Future object that represents the status and result of the task. You can use the get() method on the Future object to wait for the task to complete and retrieve its result.

Here is an example of a simple Callable implementation:

import java.util.concurrent.Callable;

public class MyCallable implements Callable<Integer> {
    private int number;

    public MyCallable(int number) {
        this.number = number;
    }

    public Integer call() throws Exception {
        int sum = 0;
        for (int i = 1; i <= number; i++) {
            sum += i;
        }
        return sum;
    }
}

In this example, MyCallable implements the Callable interface and calculates the sum of numbers from 1 to a given number. The call() method returns an Integer value, which represents the sum.

To use this Callable object, you can submit it to an ExecutorService like this:

ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(new MyCallable(100));
int result = future.get();
System.out.println("Result: " + result);
executor.shutdown();

In this example, we create a new ExecutorService with a single thread and submit a MyCallable object with an argument of 100. We use the get() method on the returned Future object to wait for the task to complete and retrieve its result. Finally, we shut down the ExecutorService.