Skip to content

Instantly share code, notes, and snippets.

@chirino
Forked from viktorklang/minscalaactors.scala
Created May 24, 2012 16:51
Show Gist options
  • Save chirino/2782734 to your computer and use it in GitHub Desktop.
Save chirino/2782734 to your computer and use it in GitHub Desktop.
Minimalist Scala Actors using HawtDispatch
// ©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"
@viktorklang
Copy link

Exposing "this" to another thread in the constructor is verboten :-)

@chirino
Copy link
Author

chirino commented May 24, 2012

Ok.. back to the original form then. :)

@viktorklang
Copy link

:-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment