Search code examples
javamultithreadingexecutorserviceexecutorexecutors

Should I call cancel(true) on Future<?> or my own FutureTask


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?


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.