Question

I have the following code,and I expected a.success(burncpu(14969)) to return instantly since it's run in a future, but why it took a long time to run.

import scala.concurrent._
val a=Promise[Unit]()
// why the following took long time here, shouldn't it be in async mode, and return very quick
a.success(burncpu(14969))  
a.future


def burncpu(a:Int):Int = {
  val point=new Date().getTime()
  while ((new Date()).getTime()-point< a) {
    a
  }
  a
}        
Was it helpful?

Solution

You are using the Promise wrong.

a.success method completes the promise with given argument, it doesn't run the expression you pass to it asynchronously.

What you probably want to do is something like this:

val f = Future(burncpu(6000))

Assuming you have an ExecutionContext available (if you don't, you can do import ExecutionContext.Implicits.global), this will construct a Future which will run your function asynchronously.

You can see how it works in Scala REPL (f.value returns None until the method has returned)

scala> val f = Future(burncpu(6000))
f: scala.concurrent.Future[Int] = scala.concurrent.impl.Promise$DefaultPromise@4d4d8fcf

scala> f.value
res27: Option[scala.util.Try[Int]] = None

scala> f.value
res28: Option[scala.util.Try[Int]] = None

scala> f.value
res29: Option[scala.util.Try[Int]] = Some(Success(6000))

OTHER TIPS

Promise.success is not executed asynchronously, basically your code is the equivalent of:

Future.successful(burncpu(14969))

You could try this:

Future {
  burncpu(14969)
}

This will call Future.apply and execute your function asynchronously.

The call to future is indeed called asynchronously. However, nothing in the API suggests that completing the Promise, i.e. calling success in your case, will be executed asynchronously. That is your responsibility to ensure.

It makes sense when you consider what a Promise is - a "marker" to another execution path, notifying it that a calculation has been completed and a result (or failure) is available.

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