-
-
Save chirino/2782734 to your computer and use it in GitHub Desktop.
Minimalist Scala Actors using HawtDispatch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ©2012 Viktor Klang | |
// ©2012 Hiram Chirino | |
object Actor { | |
import org.fusesource.hawtdispatch._ | |
type Behavior = Any => Effect | |
sealed trait Effect extends (Behavior => Behavior) | |
case object Stay extends Effect { def apply(old: Behavior): Behavior = old } | |
case class Become(like: Behavior) extends Effect { def apply(old: Behavior): Behavior = like } | |
final val Die = Become(msg => { println("Dropping msg [" + msg + "] due to severe case of death."); Stay }) // Stay Dead plz | |
sealed abstract class Address { def !(msg: Any): Unit } // The notion of an Address to where you can post messages to | |
def apply(queue:DispatchQueue)(initial: Address => Behavior): Address = new Address { // Seeded by the self-reference that yields the initial behavior | |
private var behavior: Behavior = { case self: Address => Become(initial(self)) } // Rebindable top of the mailbox, bootstrapped to identity | |
override final def !(msg: Any): Unit = behavior match { // As an optimization, we peek at our threads local copy of our behavior to see if we should bail out early | |
case dead @ Die.`like` => dead(msg) // Efficiently bail out if we're _known_ to be dead | |
case _ => queue { behavior = behavior(msg)(behavior) } // Schedule to run on the queue | |
} | |
} match { case a: Address => a ! a; a } // Make the actor self aware by seeding its address to the initial behavior | |
} | |
//Usage | |
import Actor._ | |
import org.fusesource.hawtdispatch._ | |
//Creates an actor that will, after it's first message is received, Die | |
val actor = Actor(createQueue("example"))( self => msg => { println("self: " + self + " got msg " + msg); Die } ) | |
actor ! "foo" | |
actor ! "foo" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ok.. back to the original form then. :)