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

Dave :

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.

michalk :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=105182&siteId=1