improved perf with 25 % + renamed FutureResult -> Future + Added lightweight future factory method

This commit is contained in:
Jonas Bonér 2010-03-01 22:03:17 +01:00
parent 47d19119a5
commit 15ed113112
9 changed files with 60 additions and 92 deletions

View file

@ -2,22 +2,37 @@
* Copyright (C) 2009-2010 Scalable Solutions AB <http://scalablesolutions.se>
*/
/**
* Based on code from the actorom actor framework by Sergio Bossa [http://code.google.com/p/actorom/].
*/
package se.scalablesolutions.akka.dispatch
import java.util.concurrent.locks.ReentrantLock
import java.util.concurrent.{SynchronousQueue, TimeUnit}
import java.util.concurrent.TimeUnit
class FutureTimeoutException(message: String) extends RuntimeException(message)
object Futures {
def awaitAll(futures: List[FutureResult]): Unit = futures.foreach(_.await)
def awaitOne(futures: List[FutureResult]): FutureResult = {
var future: Option[FutureResult] = None
/**
* <pre>
* val future = Futures.future(1000) {
* ... // do stuff
* }
* </pre>
*/
def future(timeout: Long)(body: => Any): Future = {
val promise = new DefaultCompletableFuture(timeout)
try {
promise completeWithResult body
} catch {
case e => promise completeWithException (None, e)
}
promise
}
def awaitAll(futures: List[Future]): Unit = futures.foreach(_.await)
def awaitOne(futures: List[Future]): Future = {
var future: Option[Future] = None
do {
future = futures.find(_.isCompleted)
} while (future.isEmpty)
@ -25,7 +40,7 @@ object Futures {
}
/*
def awaitEither(f1: FutureResult, f2: FutureResult): Option[Any] = {
def awaitEither(f1: Future, f2: Future): Option[Any] = {
import Actor.Sender.Self
import Actor.{spawn, actor}
@ -54,7 +69,7 @@ object Futures {
*/
}
sealed trait FutureResult {
sealed trait Future {
def await
def awaitBlocking
def isCompleted: Boolean
@ -64,12 +79,13 @@ sealed trait FutureResult {
def exception: Option[Tuple2[AnyRef, Throwable]]
}
trait CompletableFutureResult extends FutureResult {
trait CompletableFuture extends Future {
def completeWithResult(result: Any)
def completeWithException(toBlame: AnyRef, exception: Throwable)
}
class DefaultCompletableFutureResult(timeout: Long) extends CompletableFutureResult {
// Based on code from the actorom actor framework by Sergio Bossa [http://code.google.com/p/actorom/].
class DefaultCompletableFuture(timeout: Long) extends CompletableFuture {
private val TIME_UNIT = TimeUnit.MILLISECONDS
def this() = this(0)