Created
November 15, 2010 23:06
-
-
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.
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
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) | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Obsolete now. The current version is at http://github.com/przemek-pokrywka/wrasse3/blob/master/src/main/scala/wrasse3/GateActor.scala