Recently I worked with ThreadPoolExecutor and priorityqueue and came across both methods future.cancel() on a future task.
And task.remove() on the task it self, to remove it from the queue.
What is the better option? is there any difference? I can save list of both (the future object received from submit() or the tasks themselves), not sure what to use...
I used the following:
The false in the cancel is because I only want to remove a queue task, if it runs, let it finish.
The Javadoc for
ThreadPoolExecutor.remove() states that it may "fail to remove tasks that have been converted into other forms before being placed on the internal queue", so I wouldn't recommend calling it unless you are sure the task wasn't converted internally.
Given that, if you have a
Future, I would recommend canceling it by calling
Future.cancel(). This has the added advantage of doing the right thing if someone else has a reference to the
Future and decides to call
If you are paranoid about the amount of heap used by the cancelled tasks, you can call
ThreadPoolExecutor.purge() after calling
By the way, the
ThreadPoolExecutor.purge() method only removes Futures that have been canceled, so calling
remove() is likely a no-op.
I would use the one which is more natural for you. Without further information that is most likely the
remove/purge is much more expensive and only really needed if you are concerned you will have so many of these tasks they might be using too much memory.
The difference is pretty self explanatory, cancel just cancels the task. remove/purge removes the task from the queue.
If you expect
cancel to be overridden or your main concern is memory footprint then use
remove/purge. But in any other case I would go for