Created
May 12, 2012 01:51
-
-
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).
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
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