ExecutorService executor = Executors.newFixedThreadPool(2);
Future<Integer> calculate(Integer input) {
return executor.submit(() -> {
Thread.sleep(3000);
return input * input;
});
}
public static void main(String []args) throws Exception {
Main m = new Main();
System.out.println(m.calculate(5).get());
System.out.println("Main");
We submit Callable to Executor with 2 threads, but when i tell m.calculate(5).get()
it block main thread.
So, I can't understand, when and why should I use Future
if it blocks the main thread and doesn't run asynchronously?
Future
itself here. theget
method waits for it to complete and returns the future's return value, so by callingget
you are explicitly blocking the main thread.Future
was not created for asynchronous task withot blocking ?get()
that's blocking. You can do anything you want before you callget()
and the task represented by theFuture
will run concurrently with whatever else you're doing.get
. What else do you expectget
to do if the result is not ready? You can check if the result is ready withisDone()