Search code examples
javamultithreadingconcurrency

Futuretask doesn't work


I created a FutureTask in an analog way to what is presented in Brian Goetz's book Java Concurrency in Practice (the code sample can be found here, listing 5.12).

The problem is that the task times out even if given 10 seconds. The task just returns true so there shouldn't be a reason for it to happen:

public static void main(String[] args) throws Exception {

    FutureTask<Boolean> task = new FutureTask<>(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            return true;
        }
    });

    System.out.println(task.get(10, TimeUnit.SECONDS));
}

This code prints:

Exception in thread "main" java.util.concurrent.TimeoutException
    at java.util.concurrent.FutureTask.get(Unknown Source)
    at Main.main(Main.java:19)

Solution

  • You haven't executed the task. There will never be a result available. The javadoc states

    This class provides a base implementation of Future, with methods to start and cancel a computation, query to see if the computation is complete, and retrieve the result of the computation. The result can only be retrieved when the computation has completed

    Submit the task to an ExecutorService to be run asynchronously.

    Executors.newSingleThreadExecutor().submit(task); // ideally shutdown the ExecutorService afterwards
    

    or run it synchronously

    task.run();
    

    In the links you've given, I'm assuming the start() method which runs the FutureTask in a new Thread is called before attempting to get the result.