Question

I have a custom class MyFutureTask extends FutureTask<Void> upon which I do some code on the done() method.

I use an ExecutorService which I call submit(new MyFutureTask()) into it.

Now I can keep a reference to the Future<?> that gets returned after you call submit, but when I call cancel to that the isCancelled() method never returns true.

Should I ignore the Future<?> object that gets returned and instead work with MyFutureTask and call cancel(true) on that instead?

What is the use of the Future<?> object then?

edit: What's the difference between Future and FutureTask in Java? from this thread I understand the difference.

Besides the default cancel behavior I also want to attempt to stop a network call in progress so I guess the route I am going to use FutureTask is correct. Someone can confirm?

Was it helpful?

Solution

Don't use Executor.submit, instead use Executor.execute since you already have a Future. When you call submit, you are just needlessly wrapping your FutureTask in another FutureTask.

OTHER TIPS

Also you can't "stop" a network trip. You have to wait until it returns or times out. What you do is call Future.cancel(true), then when your network trip returns look and see if the future has been canceled Future.isCancelled(). THen you can just stop doing what you were doing in the Future. For all intents and purposes it's the same effect as if you could cancel a network trip. To the end user (ie the client code or caller) it will appear the same way. The only side effect you might notice is if you have only a single thread executing tasks in which case the thread waiting on the network trip has to return before it will pick up the next task. If that's a problem using a pool of threads.

As an aside if you used NIO or some library thereof you could stop waiting on the result immediately, but that's a lot more work to code up.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top