Junior — Middle
Is the get method of the Future class a synchronous call that blocks program execution until the result is obtained?
sobes.tech AI
Answer from AI
The get() method of the Future class in Java is a blocking call. This means that if the computation result is not yet ready, calling get() will suspend the current thread until the result becomes available.
Example:
Future<String> future = executorService.submit(() -> {
Thread.sleep(1000); // simulate a long operation
return "Result";
});
// This call will block the thread until the task completes
String result = future.get();
System.out.println(result);
To avoid blocking, you can use the get(long timeout, TimeUnit unit) method with a timeout or work with CompletableFuture, which supports non-blocking operations and callbacks.