简体   繁体   English

Future.cancel(true) 是否从队列中删除任务?

[英]Does Future.cancel(true) remove the task from the queue?

I am a little confused on the behavior of Future.cancel(true) .我对Future.cancel(true)的行为有点困惑。 It does interrupt the task if it is already running but what about the ones that have not yet started?如果它已经在运行,它确实会interrupt任务,但是那些尚未启动的任务呢? They do get cancelled but are they removed from the queue or not?他们确实被取消了,但他们是否从队列中删除? In Stackoverflow I found contradcting answers:Stackoverflow我发现了矛盾的答案:

Does not remove the task from the queue不从队列中移除任务

Does remove the task from the queue是否从队列中删除任务

Can someone explain the actual behavior?有人可以解释实际行为吗?

In case of futures representing jobs of the commonly used ThreadPoolExecutor , cancelled tasks are not immediately removed from the queue, as the method purge() indicates:在表示常用ThreadPoolExecutor作业的期货的情况下,取消的任务不会立即从队列中删除,如方法purge()所示:

purge()

Tries to remove from the work queue all Future tasks that have been cancelled.尝试从工作队列中删除所有已取消的Future任务。 This method can be useful as a storage reclamation operation, that has no other impact on functionality.此方法可用作存储回收操作,对功能没有其他影响。 Cancelled tasks are never executed, but may accumulate in work queues until worker threads can actively remove them.取消的任务永远不会执行,但可能会在工作队列中累积,直到工作线程可以主动删除它们。 Invoking this method instead tries to remove them now.现在调用此方法会尝试删除它们。 However, this method may fail to remove tasks in the presence of interference by other threads.但是,这种方法可能会在存在其他线程干扰的情况下无法删除任务。

In case of CompletableFuture , it's not said explicitly, but since the CompletableFuture operates on the Executor abstraction and has no control over the implementation at all, we can assume that it won't remove cancelled jobs from any queue.CompletableFuture情况下,没有明确说明,但由于CompletableFutureExecutor抽象上运行并且根本无法控制实现,我们可以假设它不会从任何队列中删除取消的作业。 But if the prerequisites were not fulfilled at the point of cancellation (ie when you use asyncJob.thenApplyAsy(…, someExecutor) and cancel it before asyncJob has been completed), the job might not get enqueued in the first place.但是,如果在取消时未满足先决条件(即,当您使用asyncJob.thenApplyAsy(…, someExecutor)并在asyncJob完成之前取消它时),则该作业可能不会首先入队。

The only reliable source of information is official documentation, that is, Future#cancel description.唯一可靠的信息来源是官方文档,即Future#cancel描述。 It says implementation should try to remove the task from the queue, but is not obliged to do so.它说实现应该尝试从队列中删除任务,但没有义务这样做。 Since the Future is an interface, we may expect different implementations to behave differently.由于Future是一个接口,我们可能期望不同的实现有不同的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM