Junior — Middle
How can you extract the value from a Future object in your application?
sobes.tech AI
Answer from AI
In Java, the get() method is used to retrieve the value from a Future object. This method blocks the current thread until the computation is complete and returns the result. If the computation completes with an exception, get() throws an ExecutionException.
Example:
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(() -> {
// Some long-running operation
Thread.sleep(1000);
return 42;
});
try {
Integer result = future.get(); // blocks until the result is ready
System.out.println("Result: " + result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
executor.shutdown();
There is also a get(long timeout, TimeUnit unit) method, which allows setting a maximum wait time for the result.