开发者

Is it OK to use blocking actor messages when they are wrapped in a future?

My current application is based on akka 1.1. It has multiple ProjectAnalysisActors each responsible for handling analysis tasks for a specific project. The analysis is started when such an actor receives a generic start message. After finishing one step it sends itself a message with the next step as long one is defined. The executing code basically looks as follows


sealed trait AnalysisEvent {
   def run(project: Project): Future[Any]
   def nextStep: AnalysisEvent = null
}

case class StartAnalysis() extends AnalysisEvent {
   override def run ...
   override def nextStep: AnalysisEvent = new FirstStep
}

case class FirstStep() extends AnalysisEvent {
   override def run ...
   override def nextStep: AnalysisEvent = new SecondStep
}

case class SecondStep() extends AnalysisEvent {
   .开发者_开发知识库..
}

class ProjectAnalysisActor(project: Project) extends Actor {

    def receive = {
        case event: AnalysisEvent =>
            val future = event.run(project)
            future.onComplete { f =>
                self ! event.nextStep
            }
    }

}

I have some difficulties how to implement my code for the run-methods for each analysis step. At the moment I create a new future within each run-method. Inside this future I send all follow-up messages into the different subsystems. Some of them are non-blocking fire-and-forget messages, but some of them return a result which should be stored before the next analysis step is started.

At the moment a typical run-method looks as follows


def run(project: Project): Future[Any] = {
    Future {
        progressActor ! typicalFireAndForget(project.name)
        val calcResult = (calcActor1 !! doCalcMessage(project)).getOrElse(...)

        val p: Project = ... // created updated project using calcResult

        val result = (storage !! updateProjectInformation(p)).getOrElse(...)
        result
    }
}

Since those blocking messages should be avoided, I'm wondering if this is the right way. Does it make sense to use them in this use case or should I still avoid it? If so, what would be a proper solution?


Apparently the only purpose of the ProjectAnalysisActor is to chain future calls. Second, the runs methods seems also to wait on results to continue computations.

So I think you can try refactoring your code to use Future Composition, as explained here: http://akka.io/docs/akka/1.1/scala/futures.html

def run(project: Project): Future[Any] = {
  progressActor ! typicalFireAndForget(project.name)
  for( 
      calcResult <- calcActor1 !!! doCalcMessage(project);
      p = ... // created updated project using calcResult
      result <- storage !!! updateProjectInformation(p)
  ) yield (
    result
  )
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜