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

Low-Level Primitives

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).

Higher-Level Functions & Macros

Two macros facilitate composing promises:

    then [promise binding-form & body]
    recover [promise symbol & body]

The then macro waits for the promise to be delivered successfully and executes body in a callback with the value of the promise bound to binding-form. It returns a new promise which will be delivered with the value of body. If the promise fails or if body throws an exception, then propagates the exception to the returned promise.

The recover macro catches exceptions thrown from a failed promise, executes body with the exception bound to symbol, and returns a new promise which will be delivered with the value of body. If the promise does not fail, recover propagates its value to the returned promise. This behavior is intended to be similar to try/catch.

These macros can be composed with the threading macro:

The then and recover macros are implemented in terms of two functions, then-call and recover-call, which take functions as arguments.

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.

Further Analysis

Delivery

The APIs in this proposal can be delivered either as a library or as an extension to the Clojure language.

Extending the Clojure language has the benefits of enhancing the existing promise and future in a standard way. Having a standard mechanism for callbacks at the language level will facilitate sharing callbacks across different libraries and frameworks.

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 (Scala does this). 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:

Java Interop

Promises implement java.util.concurrent.Future. Extending them to similar APIs such as Guava's ListenableFuture is trivial.

Cancellation

There is no API to remove or cancel a callback created with attend. However, it is possible to deliver a value to the promise returned by the then macro before the underlying promise is delivered. In that case, the callback function will not be executed. There is an implicit race condition with cancellation, so this cannot guarantee that the callback function will never be executed at all.

Futures can still be cancelled with future-cancel, which attempts to stop the Future's thread.

Calling future-cancel on a promise is equivalent to calling fail with an instance of java.util.concurrent.CancellationException.

Progress Reporting

Promises do not provide an API to report partial progress during a long-running operation. Progress reporting can be handled through other means such as watches.

ClojureScript

Promises can be implemented in ClojureScript, subject to the following limitations:

  • There is no notion of executors apart from "execute immediately" or "execute asynchronously" (e.g., with setTimeout)
  • deref on an unrealized promise cannot block; instead it throws an exception

Discussions

Implementations

References / Related Work

Comparison to Guava ListenableFuture

Guava's ListenableFuture takes the same basic approach of passing a Runnable and an Executor for the callback. It should be trivial to extend the INotify and IDeliver protocols to Guava's ListenableFuture and SettableFuture.

The implementation in Guava is more sophisticated than the one in cljque, using an AbstractQueuedSynchronizer instead of monitors. 

Labels: