Question

I have a class currently called Promise that works as follows:

  1. It holds a future value
  2. It can always accept a subsequent action to take that uses the future value as the parameter
  3. When the value is completed the function queue launches
  4. Any functions added after the future is complete happen synchronously

So this seems to be a design pattern from functional programming that we're jamming into Java. The important thing is that we can daisy-chain on delayed events, which I understand is a feature more built into C# 3.0 language but you have to hack together with Java classes. Unfortunately, one, I don't know a better name for this than "promise" or "future," which seem misleading since the focus is more on the "DelayedCallStack" then the value at hand, and two, I don't know of any way to do this beyond writing our own fairly complicated Promise class. Ideally I'd like to lift this from the functional Java library but the concept eludes me thus far.

Note Java doesn't even give language/library support for an asynchronous callback that takes a parameter, which is one reason I'm so pessimistic about being able to find this.

So, what is this pattern, can it be done in libraries?

Was it helpful?

Solution

Take a look a ListenableFuture in Guava:

http://code.google.com/p/guava-libraries/wiki/ListenableFutureExplained

ListenableFuture allows you to add callbacks to be executed when the Future computation is completed. You can control what thread pool the callbacks get executed under, so they can be executed synchronously or asynchronously.

OTHER TIPS

I can only say that we implemented pretty much exactly the same thing in Flex (ActionScript) and we also called it a Promise. In Clojure a promise is something quite a bit more lightweight: the get operation on it blocks until another thread delivers the promise. It's basically a one-element queue except that it retains its value forever, so subsequent gets always succeed.

What you have is a kind of a promise coupled with observers of its value. I'm not aware of any special term covering exactly that case.

EDIT

Now I notice that your "promise/future" might own the code that produces its future value (at least it's not entirely obvious whether it does). The ActionScript implementation I mentioned didn't do that -- it behaved like Clojure's, the value being supplied from the outside. I think this is the key distinction between a future and a promise.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top