Sobes.tech
Middle

What is Future in Java?

sobes.tech AI

Answer from AI

Future in Java represents the result of an asynchronous operation. It contains methods to check if the operation is complete, wait for its completion, and retrieve its result.

Main methods:

  • boolean isDone(): Returns true if the task is completed.
  • V get(): Waits for the task to complete and returns its result. If the task threw an exception, it throws it. Blocking call.
  • V get(long timeout, TimeUnit unit): Waits for the task to complete within the specified time and returns the result. Throws TimeoutException on timeout. Blocking call.
  • boolean cancel(boolean mayInterruptIfRunning): Attempts to cancel the execution of the task. Returns false if the task is already completed, canceled, or cannot be canceled for other reasons.
  • boolean isCancelled(): Returns true if the task was canceled before normal completion.

Future is usually returned when submitting a Callable or Runnable to an ExecutorService.

Example usage:

import java.util.concurrent.*;

// Example Callable that performs some work
public class MyTask implements Callable<String> {

    private final String name;

    public MyTask(String name) {
        this.name = name;
    }

    @Override
    public String call() {
        try {
            TimeUnit.SECONDS.sleep(2); // Simulate long work
            System.out.println("Task \"" + name + "\" finished");
            return "Result of " + name;
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return "Task \"" + name + "\" interrupted";
        }
    }
}
import java.util.concurrent.*;

public class FutureExample {

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        // Submit a task for execution and get a Future
        Future<String> future = executor.submit(new MyTask("Task 1"));

        System.out.println("Task submitted");

        // Check if the task is done
        while (!future.isDone()) {
            System.out.println("Task is not yet done...");
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }

        try {
            // Get the result of the task
            String result = future.get();
            System.out.println("Task completed. Result: " + result);
        } catch (InterruptedException | ExecutionException e) {
            System.err.println("Error executing task: " + e.getMessage());
        } finally {
            executor.shutdown(); // Always shut down the ExecutorService
        }
    }
}

Future is a basic interface. In Java 8, CompletableFuture was introduced, which provides more extensive capabilities for composing and handling asynchronous operations.

What is Future in Java? — Java - sobes.tech