我的实际用例是MyActor收到一条消息以开始工作。该工作需要下载几个网页,因此要求MyActor下载。每当文章完成下载时,MyActor都会做出响应。

我的代码是否有更好的设计模式?似乎允许多个参与者更新count变量似乎是不好的,因为我只关心每个参与者特定的计数。

主角:

val count = 0

def receive = {
    case CountUpdate => count += 1
    case Job => {

        List(1, 2, 3).map{case num =>
            (new myActor ? ToDownload)

            val tries = 0
            while (tries < 10){
               print("Count is: " + count)
               tries += 1
               // sleep 10 seconds
            }

            count = 0
        }
    }
}


我的演员:

def receive = {
    case ToDownload => sender ! CountUpdate
}


编辑:

如果我遵循使用期货的建议,这会不会导致竞争状况?

 var downloads: List[Int] = List()

 urls.map{ case url => Future{ download(url) }.onComplete{
    case Success(value) => downloads = downloads :+ value
    case Failure(value) => println("Failure")
    }
 }

最佳答案

您也可以创建一个Future来下载资源。未来完成后,您可以向主演员发送更新消息,主演员可以对此做出反应。 FutureexecutionContext执行。

class MainActor extends Actor {
  var count = 0

  override def receive: Receive = {
    case CountUpdate =>
      count += 1
      println("New count " + count)
    case Job =>
      val batchIDs = List(1, 2, 3)

      implicit val executionContext = ExecutionContext.fromExecutor(new ForkJoinPool())

      batchIDs.map {
        batchID =>
          Future {
            // do some work
          }.onSuccess{
            case _ => self ! CountUpdate
          }
      }
  }
}

关于java - 如何处理多个Akka Actor ?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32613322/

10-09 03:13