Why should concurrent.futures' "finishing methods" only be used by Executor implementations and unit tests"?

Viewed 83

The documentation of concurrent.futures.Future.set_result() says

This method should only be used by Executor implementations and unit tests.

The same says the documentation of set_exception() and set_running_or_notify_cancel()`.

But I can imagine using (and in Java also have used in the past) Future objects for (slightly) other purposes resp. in slightly different circumstances. In these cases, I'd just like to use a Future object. Why is this discouraged?

In order to become a little clearer: I talk about a quite complex sequence of events which involve two different schedulers and stuff, and a Future object could be used to cancel this process as well as notify about its completion. This framework is not an Executor (nor can it be one).

1 Answers

What the documentation says is that the set_result() method, not the Future object itself, should only be used by an implementation.

The rationale seems obvious to me: The result of a future should be the outcome of the work encapsulated by the Future object, but the work itself (the code that you want to run asynchronously) should not care how it is being executed. So who should be allowed to define what the result() method returns? Only the framework that schedules and launches the tasks.

In your example, you can pass Future objects around, cancel them or check their status or retrieve the result (with result()). None of these operations require you to use set_result(). But as you explained in the comments, your framework is not based on the Executor class (by inheritance or by implementing the Executor interface) but still it is an Executor work-alike. Therefore, I would say using the set_result() method is in conformance with the spirit of the comment that are concerned about.

Incidentally, have you considered tweaking your framework so that it does offer a compatible implementation of the Executor interface? It would be conceptually nice and might make some things easier to maintain and work with in the future.

Related