Junior — Middle
How to extract a string result from a Future object?
sobes.tech AI
Answer from AI
In Java, the Future<String> object represents the result of an asynchronous operation that can be obtained in the future. To extract the string value from such an object, you need to call the get() method, which blocks the current thread until the result is ready.
Example:
import java.util.concurrent.*;
public class FutureExample {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(() -> {
Thread.sleep(1000); // simulate a long operation
return "Result";
});
// Get the result (blocks if the result is not yet ready)
String result = future.get();
System.out.println(result);
executor.shutdown();
}
}
If you need to get the result without blocking, you can use the isDone() method to check readiness, but then you will have to handle the case when the result is not yet available.