pekko/akka-actor/src/main/scala/dataflow/DataFlowVariable.scala

196 lines
5.8 KiB
Scala
Raw Normal View History

2009-03-12 21:19:21 +01:00
/**
2009-12-27 16:01:53 +01:00
* Copyright (C) 2009-2010 Scalable Solutions AB <http://scalablesolutions.se>
2009-03-12 21:19:21 +01:00
*/
package akka.dataflow
2009-03-12 21:19:21 +01:00
import java.util.concurrent.atomic.AtomicReference
import java.util.concurrent.{ConcurrentLinkedQueue, LinkedBlockingQueue}
import akka.actor.{Actor, ActorRef}
import akka.actor.Actor._
import akka.dispatch.CompletableFuture
import akka.AkkaException
import akka.japi.{ Function, SideEffect }
2009-12-08 16:17:22 +01:00
2009-04-27 20:06:48 +02:00
/**
* Implements Oz-style dataflow (single assignment) variables.
2009-12-08 16:17:22 +01:00
*
2009-04-27 20:06:48 +02:00
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
2009-12-08 16:17:22 +01:00
object DataFlow {
object Start
object Exit
2009-12-08 16:17:22 +01:00
class DataFlowVariableException(msg: String) extends AkkaException(msg)
/** Executes the supplied thunk in another thread
*/
def thread(body: => Unit): Unit = spawn(body)
2009-03-12 21:19:21 +01:00
/** Executes the supplied SideEffect in another thread
* JavaAPI
*/
def thread(body: SideEffect): Unit = spawn(body.apply)
/** Executes the supplied function in another thread
*/
2009-12-08 16:17:22 +01:00
def thread[A <: AnyRef, R <: AnyRef](body: A => R) =
actorOf(new ReactiveEventBasedThread(body)).start
2009-12-08 16:17:22 +01:00
/** Executes the supplied Function in another thread
* JavaAPI
*/
def thread[A <: AnyRef, R <: AnyRef](body: Function[A,R]) =
actorOf(new ReactiveEventBasedThread(body.apply)).start
2009-12-08 16:17:22 +01:00
private class ReactiveEventBasedThread[A <: AnyRef, T <: AnyRef](body: A => T)
extends Actor {
def receive = {
case Exit => self.stop
case message => self.reply(body(message.asInstanceOf[A]))
2009-03-12 21:19:21 +01:00
}
}
private object DataFlowVariable {
private sealed abstract class DataFlowVariableMessage
private case class Set[T <: Any](value: T) extends DataFlowVariableMessage
private object Get extends DataFlowVariableMessage
}
2009-04-27 20:06:48 +02:00
/**
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
sealed class DataFlowVariable[T <: Any](timeoutMs: Long) {
import DataFlowVariable._
2009-12-08 16:17:22 +01:00
def this() = this(1000 * 60)
2009-12-08 16:17:22 +01:00
2009-03-12 21:19:21 +01:00
private val value = new AtomicReference[Option[T]](None)
2010-05-06 08:13:12 +02:00
private val blockedReaders = new ConcurrentLinkedQueue[ActorRef]
2009-03-12 21:19:21 +01:00
2009-12-08 16:17:22 +01:00
private class In[T <: Any](dataFlow: DataFlowVariable[T]) extends Actor {
self.timeout = timeoutMs
2009-12-08 16:17:22 +01:00
def receive = {
case s@Set(v) =>
if (dataFlow.value.compareAndSet(None, Some(v.asInstanceOf[T]))) {
while(dataFlow.blockedReaders.peek ne null)
dataFlow.blockedReaders.poll ! s
2009-03-12 21:19:21 +01:00
} else throw new DataFlowVariableException(
"Attempt to change data flow variable (from [" + dataFlow.value.get + "] to [" + v + "])")
case Exit => self.stop
2009-12-08 16:17:22 +01:00
}
2009-03-12 21:19:21 +01:00
}
2009-12-08 16:17:22 +01:00
private class Out[T <: Any](dataFlow: DataFlowVariable[T]) extends Actor {
self.timeout = timeoutMs
private var readerFuture: Option[CompletableFuture[Any]] = None
2009-12-08 16:17:22 +01:00
def receive = {
2010-08-23 16:06:52 +02:00
case Get => dataFlow.value.get match {
case Some(value) => self reply value
case None => readerFuture = self.senderFuture
}
case Set(v:T) => readerFuture.map(_ completeWithResult v)
case Exit => self.stop
2009-12-08 16:17:22 +01:00
}
2009-03-12 21:19:21 +01:00
}
2009-12-08 16:17:22 +01:00
private[this] val in = actorOf(new In(this)).start
2009-03-12 21:19:21 +01:00
/** Sets the value of this variable (if unset) with the value of the supplied variable
*/
2010-08-24 13:11:41 +02:00
def <<(ref: DataFlowVariable[T]) {
if (this.value.get.isEmpty) in ! Set(ref())
else throw new DataFlowVariableException(
"Attempt to change data flow variable (from [" + this.value.get + "] to [" + ref() + "])")
}
2009-03-12 21:19:21 +01:00
/** Sets the value of this variable (if unset) with the value of the supplied variable
* JavaAPI
*/
def set(ref: DataFlowVariable[T]) { this << ref }
/** Sets the value of this variable (if unset)
*/
2010-08-24 13:11:41 +02:00
def <<(value: T) {
if (this.value.get.isEmpty) in ! Set(value)
else throw new DataFlowVariableException(
"Attempt to change data flow variable (from [" + this.value.get + "] to [" + value + "])")
}
2009-12-08 16:17:22 +01:00
/** Sets the value of this variable (if unset) with the value of the supplied variable
* JavaAPI
*/
def set(value: T) { this << value }
/** Retrieves the value of variable
* throws a DataFlowVariableException if it times out
*/
def get(): T = this()
/** Retrieves the value of variable
* throws a DataFlowVariableException if it times out
*/
2009-12-08 16:17:22 +01:00
def apply(): T = {
value.get getOrElse {
val out = actorOf(new Out(this)).start
2010-08-24 13:11:41 +02:00
val result = try {
blockedReaders offer out
(out !! Get).as[T]
} catch {
case e: Exception =>
out ! Exit
throw e
}
result.getOrElse(throw new DataFlowVariableException("Timed out (after " + timeoutMs + " milliseconds) while waiting for result"))
2009-03-12 21:19:21 +01:00
}
}
2009-12-08 16:17:22 +01:00
2010-03-30 23:58:50 +02:00
def shutdown = in ! Exit
2009-03-12 21:19:21 +01:00
}
2010-09-19 21:32:06 +02:00
/**
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
class DataFlowStream[T <: Any] extends Seq[T] {
private[this] val queue = new LinkedBlockingQueue[DataFlowVariable[T]]
def <<<(ref: DataFlowVariable[T]) = queue.offer(ref)
def <<<(value: T) = {
val ref = new DataFlowVariable[T]
ref << value
queue.offer(ref)
}
def apply(): T = {
val ref = queue.take
val result = ref()
ref.shutdown
result
}
def take: DataFlowVariable[T] = queue.take
//==== For Seq ====
def length: Int = queue.size
def apply(i: Int): T = {
if (i == 0) apply()
else throw new UnsupportedOperationException(
"Access by index other than '0' is not supported by DataFlowStream")
}
def iterator: Iterator[T] = new Iterator[T] {
private val iter = queue.iterator
def hasNext: Boolean = iter.hasNext
def next: T = { val ref = iter.next; ref() }
}
override def toList: List[T] = queue.toArray.toList.asInstanceOf[List[T]]
}
}