3

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.

Dave
  • 15,639
  • 133
  • 442
  • 830
  • Why would you want to synchronously wait for an asynchronous task to be done? That's just as good as doing the task in your current synchronous code stream. – Daniel Kamil Kozar May 23 '19 at 19:46
  • 1
    Future.get() is a blocking method. This is fundamental. – Sambit May 23 '19 at 19:47
  • If `factorial` returns a `long` (or a primitive that can be converted to a `long`) there's no need to call `new Long(...)`, Java will autobox the result for you. – Slaw May 24 '19 at 07:30

2 Answers2

1

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.

Michał Krzywański
  • 15,659
  • 4
  • 36
  • 63
  • I think, this is not the answer he is looking. He is interested to know why the loop is not working. – Sambit May 23 '19 at 19:49
0

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.

Qingfei Yuan
  • 1,196
  • 1
  • 8
  • 12