Error formatting macro: pagetree: java.lang.NullPointerException
Skip to end of metadata
Go to start of metadata
You are viewing an old version of this page. View the current version. Compare with Current  |   View Page History

Design page for Promises / Futures with callbacks.

Motivation

Clojure's future and promise provide implementations of deref that block the calling thread. There is currently no facility to invoke callback functions on values when they become available. Asynchronous styles of programming are not possible without this facility, especially in single-threaded runtimes such as ClojureScript.

Proposed APIs

promise and future will return objects implementating a new protocol, INotify, supporting a function attend with two arities:

    attend [promise fn] [promise fn executor]

This function attaches a callback to the promise/future which will be invoked on the executor when the promise is delivered with a value. (attend, transitive verb, "occur with or as a result of")

Promises also implement the new protocol IDeliver, supporting two functions:

    deliver [promise value]
    fail [promise exception]

The deliver function provides a value to the promise, invokes any pending callbacks, and releases any pending derefs. The fail function delivers an exception to the promise (see "Exceptions" below).

The behavior of deref on futures/promises does not change, except that a failed promise may throw an exception (see below).

A macro on takes a promise and a body, it executes the body when the promise is delivered with its value bound to a local:

    on [[binding-form promise] & body]

The macro on returns another promise, which will be delivered with the result of executing the body. If the body throws an exception, or if the source promise was failed, the promise returned by on will throw the same exception.

Execution Context

If not supplied, executor defaults to a dynamic Var, *callback-executor*, resolved when the callback is created, that is, at the time attend was called. This Var is initially set to the Agent send-off thread pool executor, and can be globally reset or thread-bound by applications.

Running Callbacks Locally

 

If callbacks are known to be fast, it may be more efficient to run them directly on the thread that invoked deliver. This is enabled by calling attend with a nil executor (or binding *callback-executor* to nil).

 

Guava provides a similar capability with sameThreadExecutor. It is somewhat related to the JDK's CallerRunsPolicy for rejected execution.

Exceptions

A callback function (really, any function) can do one of three things:

  • Return a value
  • Throw an exception
  • Never return at all

Failing to return is almost certainly a bug anywhere execpt on the main application thread. I assume that returning a value indicates a successful execution, while throwing an exception indicates failure. However, it is also possible to return an exception object as a value, which does not necessarily indicate failure. (For example, a logging framework might handle exceptions as values.)

Given that throwing an exception is different from returning a value, promises need to handle it on a different path. This is the fail function, which acts like deliver but takes an exception as its argument and puts the promise in a "failed" state.

When it comes time to invoke callback functions, there are several possible ways to handle failure:

  1. Provide separate callback attachment points for success and failure
  2. Pass the exception to the callback as a normal value
  3. Wrap the value or exception in a union type

Method 1 leads to a proliferation of error-handling functions. Method 2 makes it impossible to tell if the exception object was thrown or delivered as a normal value. Method 3 is more natural in a statically-typed language. In both 2 and 3 the callback function must always check whether its argument is a normal value or an exception.

I have chosen a variant of 3 by using the promise itself as the argument to the callback function. The callback is responsible for calling deref on the promise. If the promise is in a failed state, dereferencing it will throw the exception. Callback functions can use standard try/catch blocks to handle the exception or allow it to propagate. Macros such as on handle propagation automatically and allow users to program in terms of values.

Delivering a promise A as a value to another promise B causes B to attend on A. Whenever A is delivered/failed, B is delivered/failed with the same value. This makes it convenient to implement multiple try/retry operations with promises, as in this example:

(defn do-operation [tries]
  (if (zero? tries)
    (throw (ex-info "Operation failed" {}))
    (-> (future
          ;; Some long-running operation which may fail
          )
        (follow (fn [p]
                  (try @p
                       (catch Exception _
                         (do-operation (dec tries)))))))))

(retry-operation 3)

Discussions

Implementations

References / Related Work

Labels: