Sobes.tech
Junior — Middle

Explain the concept of the Future object and its use in programming.

sobes.tech AI

Answer from AI

The Future object in Java represents the result of an asynchronous operation that can be obtained in the future. It allows running tasks in a separate thread and retrieving the result later without blocking the main thread.

Main points:

  • Future provides methods to check if the task is complete (isDone()), to cancel it (cancel()), and to get the result (get()).
  • The get() method blocks the current thread until the task is finished and the result is available.

Example of usage with ExecutorService:

import java.util.concurrent.*;

ExecutorService executor = Executors.newSingleThreadExecutor();

Callable<String> task = () -> {
    Thread.sleep(1000); // simulate a long operation
    return "Result";
};

Future<String> future = executor.submit(task);

// Other actions can be performed here

try {
    String result = future.get(); // blocks until the task completes
    System.out.println(result);
} catch (InterruptedException | ExecutionException e) {
    e.printStackTrace();
}

executor.shutdown();

Thus, Future helps organize asynchronous task execution and manage their results.