Skip to content

Instantly share code, notes, and snippets.

@przemek-pokrywka
Created November 15, 2010 23:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save przemek-pokrywka/701140 to your computer and use it in GitHub Desktop.
Save przemek-pokrywka/701140 to your computer and use it in GitHub Desktop.
Here is how to capture both Gate states: open and closed without using GoF State Pattern. It looks like a thread, but it doesn't block any most of the time. Most of the previously hardcoded things are actor parameters now.
package wrasse3
import scala.actors.Actor._
import System.{currentTimeMillis => now}
import actors.{Actor, TIMEOUT}
class GateActor[R](sendRequest: => R,
errorResponse: R,
maxErrors: Int,
closePeriod: Int) extends Actor {
def info(m: String) = println(this + " " + m)
def stop() = try { exit() } catch { case _ => () }
def act = loop{
info("entering open state")
var errors = 0
loopWhile(errors < maxErrors) {
react{
case _ => {
val r = sendRequest
if (r == errorResponse) errors += 1 else errors = 0
reply(r)
}
}
} andThen {
info("entering closed state")
val end = now + closePeriod
loopWhile(now < end) {
reactWithin(end - now) {
case TIMEOUT => ()
case _ => {
info("gate is currently closed");
reply(errorResponse)
}
}
}
}
}
}
@przemek-pokrywka
Copy link
Author

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