当前位置: 动力学知识库 > 问答 > 编程问答 >

java - cancel() vs remove() on executors

问题描述:

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...

remove:

executor.remove(task);

executor.purge();

cancel:

futureObject.cancel(false);

I used the following:

http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html#remove%28java.lang.Runnable%29

The false in the cancel is because I only want to remove a queue task, if it runs, let it finish.

网友答案:

Use Future.cancel()

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 Future.get()

If you are paranoid about the amount of heap used by the cancelled tasks, you can call ThreadPoolExecutor.purge() after calling Future.cancel().

By the way, the ThreadPoolExecutor.purge() method only removes Futures that have been canceled, so calling purge() after 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 cancel

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 cancel.

分享给朋友:
您可能感兴趣的文章:
随机阅读: