Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 717
Dave Avatar asked Jan 17 '26 23:01

Dave


1 Answers

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.

like image 162
Michał Krzywański Avatar answered Jan 19 '26 14:01

Michał Krzywański



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!