Skip to content

Commit

Permalink
Make f(await(completedFuture)) execute f synchronously
Browse files Browse the repository at this point in the history
A worthy optimization, suggested by @danarmak.

Closes scala#73
  • Loading branch information
retronym committed Dec 15, 2014
1 parent c0d7115 commit 764f69f
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
7 changes: 6 additions & 1 deletion src/main/scala/scala/async/internal/FutureSystem.scala
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,12 @@ object ScalaConcurrentFutureSystem extends FutureSystem {

def onComplete[A, U](future: Expr[Fut[A]], fun: Expr[scala.util.Try[A] => U],
execContext: Expr[ExecContext]): Expr[Unit] = reify {
future.splice.onComplete(fun.splice)(execContext.splice)
val future1 = future.splice
val fun1 = fun.splice
if (future1.isCompleted)
fun1(future1.value.get) // Optimization for completed futures, see https://github.com/scala/async/issues/73
else
future1.onComplete(fun1)(execContext.splice)
}

def completeProm[A](prom: Expr[Prom[A]], value: Expr[scala.util.Try[A]]): Expr[Unit] = reify {
Expand Down
21 changes: 21 additions & 0 deletions src/test/scala/scala/async/run/SyncOptimizationSpec.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package scala.async.run

import org.junit.Test
import scala.async.Async._
import scala.concurrent._
import scala.concurrent.duration._
import ExecutionContext.Implicits._

class SyncOptimizationSpec {

@Test
def awaitOnCompletedFutureRunsOnSameThread: Unit = {
val future = async {
val thread1 = Thread.currentThread
val f = await(Future.successful(1))
val thread2 = Thread.currentThread
assert(thread1 == thread2)
}
Await.result(future, 10.seconds)
}
}
1 change: 0 additions & 1 deletion src/test/scala/scala/async/run/futures/FutureSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -538,7 +538,6 @@ class FutureSpec {
val f = async { await(future(5)) / 0 }
Await.ready(f, defaultTimeout).value.get.toString mustBe expected.toString
}

}


0 comments on commit 764f69f

Please sign in to comment.