简体   繁体   中英

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

I am a little confused on the behavior of Future.cancel(true) . It does interrupt the task if it is already running but what about the ones that have not yet started? They do get cancelled but are they removed from the queue or not? In Stackoverflow I found contradcting answers:

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:

purge()

Tries to remove from the work queue all Future tasks that have been cancelled. 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. 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.

The only reliable source of information is official documentation, that is, Future#cancel description. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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