Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Future always returning null

Tags:

java

null

future

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?

like image 240
Cydhra Avatar asked Jan 19 '17 15:01

Cydhra


1 Answers

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.

like image 193
Kayaman Avatar answered Sep 28 '22 01:09

Kayaman