Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are promises flawed?

Like the author of this question I'm trying to understand the reasoning for user-visible promises in Scala 2.10's futures and promises.

Particularly, going again to the example from the SIP, isn't it completely flawed:

import scala.concurrent.{ future, promise }
val p = promise[T]
val f = p.future
val producer = future {
  val r = produceSomething()
  p success r
  continueDoingSomethingUnrelated()
}
val consumer = future {
  startDoingSomething()
  f onSuccess {
    case r => doSomethingWithResult()
  }
}

I am imagining the case where the call to produceSomething results in a runtime exception. Because promise and producer-future are completely detached, this means the system hangs and the consumer will never complete with either success or failure.

So the only safe way to use promises requires something like

val producer = future {
  try {
    val r.produceSomething()
    p success r
  } catch {
     case e: Throwable =>
       p failure e
       throw e  // ouch
  }
  continueDoingSomethingUnrelated()
}

Which obviously error-prone and verbose.

The only case I can see for a visible promise type—where future {} is insufficient—is the one of the callback hook in M. A. D.'s answer. But the example of the SIP doesn't make sense to me.

like image 556
0__ Avatar asked Jan 15 '13 22:01

0__


1 Answers

This is why you rarely use success and failure unless you already know something is bulletproof. If you want bulletproof, this is what Try is for:

val producer = future {
  p complete Try( produceSomething )
  continueDoingSomethingUnrelated()
}

It doesn't seem necessary to throw the error again; you've already dealt with it by packing it into the answer to the promise, no? (Also, note that if produceSomething itself returns a future, you can use completeWith instead.)

like image 123
Rex Kerr Avatar answered Nov 03 '22 14:11

Rex Kerr