Sobes.tech
Middle

What is the purpose of the Future class in Java?

sobes.tech AI

Answer from AI

The Future class represents the result of an asynchronous operation. It allows you to retrieve the value after its computation, check if the operation is complete, wait for its completion, or cancel it. This is a key element for non-blocking operations in multithreaded applications.

Main methods:

  • get(): Waits for the operation to complete and returns the result. Blocking call.
  • get(long timeout, TimeUnit unit): Waits for the operation to complete with a timeout. May throw TimeoutException.
  • isDone(): Returns true if the operation is complete (successfully, with an error, or canceled).
  • isCancelled(): Returns true if the operation was canceled.
  • cancel(boolean mayInterruptIfRunning): Attempts to cancel the execution of the task.

Example of usage:

import java.util.concurrent.*;

// Example of an asynchronous task
class MyCallable implements Callable<String> {
    @Override
    public String call() throws Exception {
        Thread.sleep(1000); // Simulate work
        return "Computation result";
    }
}

public class FutureExample {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newSingleThreadExecutor();

        // Launch an asynchronous task
        Future<String> future = executor.submit(new MyCallable());

        System.out.println("Task started. Waiting...");

        // Check status non-blockingly
        while (!future.isDone()) {
            System.out.println("Task is still running...");
            Thread.sleep(100);
        }

        // Get the result (blocking call)
        String result = future.get();
        System.out.println("Result received: " + result);

        // Shutdown executor
        executor.shutdown();
    }
}

Future is often used together with ExecutorService to manage thread pools and execute tasks asynchronously. It provides a convenient way to interact with the results of parallel computations.