Dave
Dave

Reputation: 19320

How can you tell when a Future object is done with its task?

I'm using Java 8. I was wondering how you can tell when a Future object is done with its task. I tried understanding it by writing the below

    Callable<Long> c = new Callable<Long>() {

        @Override
        public Long call() throws Exception {
            return new Long(factorial(1));
        }

    };

    ExecutorService s = Executors.newFixedThreadPool(2);
    Future<Long> f = s.submit(c);

    while (!f.isDone())
    {
        System.out.println("waiting..." + f.get().toString());
    }   // while
    System.out.println(f.get().toString());

but the while loop never returns (f.isDone() is always false) even though I can tell there is a computed result.

Upvotes: 3

Views: 903

Answers (2)

Michał Krzywański
Michał Krzywański

Reputation: 16940

It works however you never shut down the pool that you have created. You can read about this in ExecutorService documentation. Add this at the end to close your pool :

s.shutdown();
try {
    if(!s.awaitTermination(3, TimeUnit.SECONDS)) {
          s.shutdownNow();
    }
} catch (InterruptedException e) {
    s.shutdownNow();
}

Further explanation :

Future::get is a blocking operation. Under some circumstances your loop might be never invoked because task maintained by future may be finished before loop condition is evaluated. But in most cases in first loop iteration you will call Future::get which is blocking operation. Then you get the result and again loop condition is evaluated to false because future is done. To conclude - your loop will be invoked 0 or 1 times. And after that you you have to close the pool as I wrote earlier.

Upvotes: 1

Qingfei Yuan
Qingfei Yuan

Reputation: 1212

No. It will be done soon. In your case, you will print "waiting... 1 " and 1.

If you debug, it will much clear.

As for the thread keep running, that because of Executors.

The threads in the pool will exist until it is explicitly shutdown.

Upvotes: 0

Related Questions