在Akka演员中使用期货 [英] Using Futures in Akka Actors

查看:87
本文介绍了在Akka演员中使用期货的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始在Scala学习Akka演员。我的理解是,Actor收到的消息在Actor的邮箱中排队,并且一次处理一次。通过一次处理一个消息,可以缓解并发问题(竞争条件,死锁)。

I'm just starting to learn Akka Actors in Scala. My understanding is that messages received by an Actor are queued in an Actor's mailbox, and processed one at a time. By processing messages one at a time, concurrency issues (race conditions, deadlocks) are mitigated.

但是,如果Actor创造了一个未来来完成与a关联的工作会发生什么?信息?由于未来是异步的,因此与先前消息关联的未来仍在运行时,Actor可以开始处理接下来的几条消息。这会不会创造比赛条件?

But what happens if the Actor creates a future to do the work associated with a message? Since the future is async, the Actor could begin processing the next several messages while the future associated with the prior message is still running. Wouldn't this potentially create race conditions? How can one safely use futures within an Actor's receive() method to do long running tasks?

推荐答案

使用期货的最安全方法是如何在Actor的receive()方法中安全地使用期货来执行长期运行的任务的?演员中的角色是将来仅使用 pipeTo 并将其结果作为消息发送给演员(可能是同一演员)。

The safest way to use futures within an actor is to only ever use pipeTo on the future and send its result as a message to an actor (possibly the same actor).

import akka.pattern.pipe

object MyActor {

  def doItAsynchronously(implicit ec: ExecutionContext): Future[DoItResult] = { 
  /* ... */ 
  }

}

class MyActor extends Actor {

  import MyActor._    
  import context.dispatcher  

  def receive = {
    case DoIt =>
      doItAsynchronously.pipeTo(self)
    case DoItResult =>
       // Got a result from doing it
  }

}

这可确保您不会使角色中的任何状态发生变异。

This ensures that you won't mutate any state within the actor.

这篇关于在Akka演员中使用期货的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆