Whether method cancel() in java.util.concurrent.Future should be blocking?

丶灬走出姿态 提交于 2019-12-21 19:31:28

问题


I'm trying to implement Future<> interface in my project. But it looks like documentation is a little bit vague for it.

From official documentation we can deduce:

  1. Method cancel() does not throw exceptions like InterruptedException or ExecutionException. Moreover it has no the variant with timeout. So it looks like, it should NOT be blocking.
  2. Documentation says

    After this method returns, subsequent calls to isDone() will always return true.

    but

    boolean isDone() Returns true if this task completed.

    So if we run cancel() while the task is processing and cannot be canceled, this method should wait until the task is finished. Which contradicts with 1.

  3. The return value of cancel() described as

    Returns: false if the task could not be cancelled, typically because it has already completed normally; true otherwise

    So, if the task is running and potentially can be cancelled but not at this exact moment, we should return true (we cannot state that it could not be cancelled) or wait (but it contradicts 1).

  4. But there is also a statement

    Subsequent calls to isCancelled() will always return true if this method returned true.

    but

    boolean isCancelled() Returns true if this task was cancelled before it completed normally.

    Which contradicts 3 in case when we run cancel() when the task is running and it cannot be said whether the task could be cancelled or not (because cancel() should return true in that case, but isCancelled() should return false).

It looks like this API have been delevoped long time ago and such inconsistences should not appear in the docs. But there are there. Do I understand something incorrectly?


回答1:


Do I understand something incorrectly?

I believe so. Future is not a job control API; it is an abstraction over the concept of a value which may not yet have been computed. By cancelling a Future you simply waive your interest in that value; the rest is up to implementation detail.

As a consequence, Future is not strongly coupled to the computation which will eventually produce its result. If you invoke cancel and it returns true, you have moved the Future to its final, unchangeable state: that of a cancelled Future, which will never produce its value. The underlying computation task may or may not go on for an indeterminate amount of time; you have no control over that through the Future's API.




回答2:


I read it as "isCancelled() returns true after cancel() returned true" and I cannot see any inconsistences



来源:https://stackoverflow.com/questions/28691081/whether-method-cancel-in-java-util-concurrent-future-should-be-blocking

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!