Hey I got a quick question about Java Futures. I broke down the problem to this snippet:
ExecutorService service = Executors.newCachedThreadPool();
try {
System.out.println(service.submit(new FutureTask<>(() -> true)).get());
} catch (InterruptedException e1) {
e1.printStackTrace();
} catch (ExecutionException e1) {
e1.printStackTrace();
}
I expect this to output "true" on my terminal. But instead it always outputs null. What am I missing?
It's the FutureTask
that's throwing off the logic.
Your () -> true
is a Callable<Boolean>
returning true
, but FutureTask
is a Runnable
which doesn't return a value. Therefore submit
returns a Future<Void>
(since it's getting a Runnable
parameter, not a Callable
), which always contains null.
Remove the unnecessary FutureTask
wrapper and just use the Callable
directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With