pekko/akka-actor/src/main/scala/dispatch/Future.scala

269 lines
6.5 KiB
Scala
Raw Normal View History

/**
2009-12-27 16:01:53 +01:00
* Copyright (C) 2009-2010 Scalable Solutions AB <http://scalablesolutions.se>
*/
package akka.dispatch
import akka.AkkaException
import akka.actor.Actor.spawn
2010-10-31 19:27:55 +01:00
import akka.routing.Dispatcher
import java.util.concurrent.locks.ReentrantLock
import java.util.concurrent.TimeUnit
import akka.japi.Procedure
class FutureTimeoutException(message: String) extends AkkaException(message)
object Futures {
/**
2010-05-12 07:40:08 +02:00
* Module with utility methods for working with Futures.
* <pre>
* val future = Futures.future(1000) {
* ... // do stuff
* }
* </pre>
2010-10-12 13:18:15 +02:00
*/
def future[T](timeout: Long,
dispatcher: MessageDispatcher = Dispatchers.defaultGlobalDispatcher)
(body: => T): Future[T] = {
val f = new DefaultCompletableFuture[T](timeout)
spawn({
try { f completeWithResult body }
catch { case e => f completeWithException e}
})(dispatcher)
f
}
2010-04-23 20:46:58 +02:00
def awaitAll(futures: List[Future[_]]): Unit = futures.foreach(_.await)
/**
* Returns the First Future that is completed
* if no Future is completed, awaitOne optionally sleeps "sleepMs" millis and then re-scans
*/
def awaitOne(futures: List[Future[_]], timeout: Long = Long.MaxValue): Future[_] = {
val futureResult = new DefaultCompletableFuture[Any](timeout)
val fun = (f: Future[_]) => futureResult completeWith f.asInstanceOf[Future[Any]]
for(f <- futures) f onComplete fun
futureResult.await
}
2010-10-15 17:24:15 +02:00
/**
* Applies the supplied function to the specified collection of Futures after awaiting each future to be completed
*/
def awaitMap[A,B](in: Traversable[Future[A]])(fun: (Future[A]) => B): Traversable[B] =
in map { f => fun(f.await) }
/*
2010-04-23 20:46:58 +02:00
def awaitEither[T](f1: Future[T], f2: Future[T]): Option[T] = {
import Actor.Sender.Self
import Actor.{spawn, actor}
2010-05-21 20:08:49 +02:00
2010-04-23 20:46:58 +02:00
case class Result(res: Option[T])
val handOff = new SynchronousQueue[Option[T]]
spawn {
try {
println("f1 await")
f1.await
println("f1 offer")
handOff.offer(f1.result)
} catch {case _ => {}}
}
spawn {
try {
println("f2 await")
f2.await
println("f2 offer")
println("f2 offer: " + f2.result)
handOff.offer(f2.result)
} catch {case _ => {}}
}
Thread.sleep(100)
handOff.take
}
*/
}
2010-04-23 20:46:58 +02:00
sealed trait Future[T] {
def await : Future[T]
2010-10-31 19:27:55 +01:00
def awaitBlocking : Future[T]
2010-10-31 19:27:55 +01:00
def isCompleted: Boolean
2010-10-31 19:27:55 +01:00
def isExpired: Boolean
2010-10-31 19:27:55 +01:00
def timeoutInNanos: Long
2010-10-31 19:27:55 +01:00
2010-04-23 20:46:58 +02:00
def result: Option[T]
2010-10-31 19:27:55 +01:00
def exception: Option[Throwable]
2010-10-31 19:27:55 +01:00
def onComplete(func: Future[T] => Unit): Future[T]
/* Java API */
def onComplete(proc: Procedure[Future[T]]): Future[T] = onComplete(f => proc(f))
2010-10-15 17:24:15 +02:00
def map[O](f: (T) => O): Future[O] = {
val wrapped = this
new Future[O] {
def await = { wrapped.await; this }
def awaitBlocking = { wrapped.awaitBlocking; this }
def isCompleted = wrapped.isCompleted
def isExpired = wrapped.isExpired
def timeoutInNanos = wrapped.timeoutInNanos
def result: Option[O] = { wrapped.result map f }
def exception: Option[Throwable] = wrapped.exception
def onComplete(func: Future[O] => Unit): Future[O] = { wrapped.onComplete(_ => func(this)); this }
2010-10-15 17:24:15 +02:00
}
}
}
2010-04-23 20:46:58 +02:00
trait CompletableFuture[T] extends Future[T] {
def completeWithResult(result: T)
def completeWithException(exception: Throwable)
def completeWith(other: Future[T]) {
val result = other.result
val exception = other.exception
if (result.isDefined) completeWithResult(result.get)
else if (exception.isDefined) completeWithException(exception.get)
//else TODO how to handle this case?
}
}
// Based on code from the actorom actor framework by Sergio Bossa [http://code.google.com/p/actorom/].
2010-04-23 20:46:58 +02:00
class DefaultCompletableFuture[T](timeout: Long) extends CompletableFuture[T] {
import TimeUnit.{MILLISECONDS => TIME_UNIT}
2010-10-31 19:27:55 +01:00
def this() = this(0)
val timeoutInNanos = TIME_UNIT.toNanos(timeout)
private val _startTimeInNanos = currentTimeInNanos
private val _lock = new ReentrantLock
private val _signal = _lock.newCondition
private var _completed: Boolean = _
2010-04-23 20:46:58 +02:00
private var _result: Option[T] = None
private var _exception: Option[Throwable] = None
private var _listeners: List[Future[T] => Unit] = Nil
def await = try {
_lock.lock
var wait = timeoutInNanos - (currentTimeInNanos - _startTimeInNanos)
while (!_completed && wait > 0) {
var start = currentTimeInNanos
try {
wait = _signal.awaitNanos(wait)
if (wait <= 0) throw new FutureTimeoutException("Futures timed out after [" + timeout + "] milliseconds")
} catch {
case e: InterruptedException =>
wait = wait - (currentTimeInNanos - start)
}
}
this
} finally {
_lock.unlock
}
def awaitBlocking = try {
_lock.lock
while (!_completed) {
_signal.await
}
this
} finally {
_lock.unlock
}
def isCompleted: Boolean = try {
_lock.lock
_completed
} finally {
_lock.unlock
}
def isExpired: Boolean = try {
_lock.lock
timeoutInNanos - (currentTimeInNanos - _startTimeInNanos) <= 0
} finally {
_lock.unlock
}
2010-04-23 20:46:58 +02:00
def result: Option[T] = try {
_lock.lock
_result
} finally {
_lock.unlock
}
def exception: Option[Throwable] = try {
_lock.lock
_exception
} finally {
_lock.unlock
}
def completeWithResult(result: T) {
val notify = try {
_lock.lock
if (!_completed) {
_completed = true
_result = Some(result)
true
} else false
} finally {
_signal.signalAll
_lock.unlock
}
if (notify)
notifyListeners
}
def completeWithException(exception: Throwable) {
val notify = try {
_lock.lock
if (!_completed) {
_completed = true
_exception = Some(exception)
true
} else false
} finally {
_signal.signalAll
_lock.unlock
}
if (notify)
notifyListeners
}
def onComplete(func: Future[T] => Unit): CompletableFuture[T] = {
val notifyNow = try {
_lock.lock
if (!_completed) {
_listeners ::= func
false
}
else
true
} finally {
_lock.unlock
}
if (notifyNow)
notifyListener(func)
this
}
private def notifyListeners() {
for(l <- _listeners)
notifyListener(l)
}
2010-10-31 19:27:55 +01:00
private def notifyListener(func: Future[T] => Unit) {
func(this)
}
2010-10-31 19:27:55 +01:00
private def currentTimeInNanos: Long = TIME_UNIT.toNanos(System.currentTimeMillis)
}