Scala actors and shared state
I am trying to implement a dispatcher actor that either process the request or delegates the processing to another actor in case of failure (actually it is the exponential backoff algorithm). The dispatcher actor has a boolean variable that is used to decide how to route the processing.
Is it correct to mantain some state in the actor? What problems could happen? Should I use a transactor (akka) or STM to avoid problems? (I am using akka actors)
class DispatcherActor extends Actor {
var backoff = false
def receive = {
case SendMessage(registrationId, message) => {
if (backoff) {
//put on the queue
backoffManagerActor ! AddMessageToQueue(message)
} else {
httpClient.sendNotificationToClient(message, this)
}
}
case BackoffCompleted => //set backoff t开发者_Python百科o false
backoff = false
}
def otherMethod = {
backoff=true
}
}
Actors should maintain state, but it's easiest to reason about them if they only change that state in response to messages or their internally-generated actions; if other entities want them to change state, they should send a message.
In your case, I'd change
def otherMethod { backoff = true }
to, within receive,
case BeginBackoff => backoff = true
and have whoever was going to call otherMethod send BeginBackoff
instead. (If you need to preferentially process the backoff messages, you should use the two-level receive others have demonstrated e.g. in response to your previous question about actors.)
精彩评论