将Akka演员包装在类中是否会导致内存泄漏? [英] Can wrapping akka actors in a class cause memory leaks?

查看:141
本文介绍了将Akka演员包装在类中是否会导致内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个围绕scala akka actorRef的相当基本的包装器类.基本上,该类具有一个字段,它是actorRef,并提供了许多将特定消息告知" actorRef的方法.通过这种方式,我可以遵循指定的API,并避免暴露出Tell或Message类.我在程序中遇到了内存泄漏,我想知道我的Akka演员包装器是否引起了问题.我在下面编写了此模拟程序以检验我的理论.

I have a fairly basic wrapper class around a scala akka actorRef. Basically the class has a field which is an actorRef and exposes a number of methods that "tell" specific messages to the actorRef. In this fashion I can adhere to a specify API and avoid exposing tells or message classes. I've experienced a memory leak in my program and I'm wondering if my wrapper around akka actors is causing the problem. I wrote this simulation below to test my theory.

import akka.actor.{ActorSystem, ActorRef, PoisonPill}
import akka.actor.ActorDSL._

implicit val as = ActorSystem()

def createMemoryActor(): ActorRef = actor(new Act {
  Array.fill(99999999)(1.0) // Just to take up memory
  become {
    case _ => print("testing memory leaks")
  }
})

val memoryActor = createMemoryActor() // memory usage jumps up

memoryActor ! PoisonPill
System.gc() // memory usage goes back down

case class ActorWrapper() {
  val memoryActor = createMemoryActor()
}

def doNothing(): Unit = {
  val shouldGetGCed = ActorWrapper()
  ()
}

doNothing() // memory usage jumps up
System.gc() // memory usage goes back down

我已经在scala repl中运行了以上代码,并运行jvisualvm来分析内存使用情况.似乎"shouldGetGCed"引用被收集了车库,并且其actorRef字段(占用了内存)也被垃圾收集了.总是这样吗?还是我想念一些东西?还有没有人有任何最佳方法来包装参与者以遵循特定的API?

I've run the above code in a scala repl and run jvisualvm to profile the memory usage. It seems that the "shouldGetGCed" reference gets garage collected and its actorRef field (which was taking up memory) also gets garbage collected. Is this always the case or am I missing something? Also anyone have any best practices for wrapping actors to adhere to specific APIs?

推荐答案

每个启动的actor最终都必须停止,直到发生这种情况,它才会消耗内存.在您的示例中,您需要shouldGetGCed.memoryActor ! PoisonPill.由于角色本质上是分布式实体,并且JVM不支持分布式GC,因此没有针对角色的自动垃圾收集.

Every actor that is started must eventually be stopped, and until that happens it will consume memory. In your example you need to e.g. shouldGetGCed.memoryActor ! PoisonPill. There is no automatic garbage collection for actors since they are distributed entities by nature and the JVM does not support distributed GC.

这篇关于将Akka演员包装在类中是否会导致内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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