【问题标题】:Akka Actors Still Available After Stopped by PoisonPill被 PoisonPill 停止后,Akka 演员仍然可用
【发布时间】:2015-06-23 00:25:26
【问题描述】:

我正在使用 akka 动态创建演员并在他们完成特定工作时将其销毁。我已经掌握了演员创建的方法,但是无论我如何终止演员,停止演员都会将他们留在记忆中。最终这会导致内存不足异常,尽管在任何给定时间我应该只有少数活跃的演员。

我用过:

self.tell(PoisonPill, self)

和:

context.stop(self)

试图摧毁演员。有什么想法吗?

编辑:这里有更多内容来充实我正在尝试做的事情。该程序打开并产生十个演员。

val system = ActorSystem("system")
(1 to 10) foreach { x => 
  Entity.count += 1
  system.actorOf(Props[Entity], name = Entity.count.toString())
}

这是实体的代码:

class Entity ()  extends Actor {
  Entity.entities += this
  val id = Entity.count
  import context.dispatcher
  val tick = context.system.scheduler.schedule(0 millis, 100 millis, self, "update")
  def receive = {
    case "update" => {
      Entity.entities.foreach(that => collide(that))
    }
  }
  override def postStop() = tick.cancel()
  def collide(that:Entity) {
    if (!this.isBetterThan(that)) {
      destroyMe()
      spawnNew()
    }        
  }
  def isBetterThan() :Boolean = {
    //computationally intensive logic
  }
  private def destroyMe(){
    Entity.entities.remove(Entity.entities.indexOf(this))
    self.tell(PoisonPill, self)
    //context.stop(self)
  }
  private def spawnNew(){
    val system = ActorSystem("system")
    Entity.count += 1
    system.actorOf(Props[Entity], name = Entity.count.toString())
  }  
}
object Entity {
  val entities = new ListBuffer[Entity]()
  var count = 0
}

【问题讨论】:

  • 你能展示更多关于你在哪里创建actor以及如何停止actor的代码吗?这些演员是否在无限地处理某些事情?
  • 请记住,仅向演员发送 PoisonPill 是不够的;演员必须仔细阅读它之前的所有消息。在实际发送 PoisonPill 消息的地方,actor 被杀死。
  • 在def spawnNew 中创建新的ActorSystem 是一个非常糟糕的主意。您可以改用context.system。 Entity.conv 和 Entity.entities 都不安全。您应该考虑使用管理这些状态的父 Actor 和一个子 Actor 来进行计算。
  • @johny 是的。我正在努力解决这个问题。

标签: scala akka actor


【解决方案1】:

感谢@AmigoNico,您为我指明了正确的方向。事实证明两者都没有

self.tell(PoisonPill, self)

也没有

context.stop(self)

为及时处理Actor而工作;我将线路切换到:

system.stop(self)

一切都按预期进行。

【讨论】:

  • 最后两种可能性没有区别,所以你的观察是有缺陷的。
猜你喜欢
  • 2015-05-06
  • 2019-01-01
  • 2017-03-18
  • 2012-10-14
  • 2015-02-04
  • 2020-08-20
  • 2014-12-02
  • 2015-08-18
  • 1970-01-01
相关资源
最近更新 更多