Sobes.tech
Junior — Middle

What is the main role of the Future interface in programming?

sobes.tech AI

Answer from AI

The Future interface in Java represents a mechanism for working with the result of an asynchronous operation. Its main role is to provide a way to obtain the result of a computation that is executed in another thread, without blocking the main thread until the result is ready.

With Future, you can:

  • Check if the asynchronous task has completed (isDone())
  • Cancel the execution of the task (cancel())
  • Get the result, waiting for it to be ready (get())

Example of usage:

ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(() -> {
    Thread.sleep(1000); // simulate a long operation
    return 42;
});

// You can perform other tasks while waiting for the result
System.out.println("Task started");

// Get the result (blocks if not ready yet)
Integer result = future.get();
System.out.println("Result: " + result);

executor.shutdown();
What is the main role of the Future interface in… - sobes.tech