Skip to content

Instantly share code, notes, and snippets.

@mardambey
Created May 12, 2012 01:51
Show Gist options
  • Save mardambey/2663670 to your computer and use it in GitHub Desktop.
Save mardambey/2663670 to your computer and use it in GitHub Desktop.
An actor wrapping an object of type T providing async get/set calls without blocking (sacrificing accuracy).
import scala.actors.Actor
case class Set(value:Any)
case class Get()
case class Destroy()
/*
* An actor wrapping an object of type T providing async get/set
* calls without blocking (sacrificing accuracy).
*
* Usage:
*
* <code>
*
* val b = new AsyncValue[Boolean](initialValue, optionalTimeout) // defaults to null and 50 millis
* b.set(true)
* b.get()
*
* </code>
*
*/
class AsyncValue[T](var value:T = null, var timeout:Int = 50) extends Actor {
/**
* Initialize default value to true
*/
/**
* Spin up and start the actor
*/
start()
def act() {
loop {
react {
// we're being asked if we can process
case Set(v:T) => {
value = v
}
case Get() => {
reply(value)
}
case Destroy() => {
exit()
}
case _ =>
}
}
}
def set(v:T) {
this ! Set(v)
}
def get() : T = {
try {
val ret = this !? (timeout, Get())
ret.get.asInstanceOf[T]
} catch {
case e:Exception => {
// This should not be the case
value
}
}
}
def destroy() {
this ! Destroy()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment