当递归调用Future [T]中的函数时,如何缓解内存泄漏? [英] How do I mitigate memory leaks when recursively calling a function inside a Future[T]?

查看:425
本文介绍了当递归调用Future [T]中的函数时,如何缓解内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题的灵感来自早期Stackoverflow中的一些评论文章对同一主题,也是一些代码我也写的好。给定其中包含的示例,我有点相信这种模式是尾递归。如果是这样,我如何减轻由累积未来的内存泄漏,其底层线程从不加入它们从中产生的ForkJoinPool?

This question is inspired by some comments in an earlier Stackoverflow article on the same topic and also motivated by some code I'm writing as well. Given the example contained therein, I'm somewhat convinced that this pattern is tail recursive. If this is the case, how do I mitigate the memory leak posed by accumulating futures whose underlying threads never join the ForkJoinPool from which they were spawned?

import com.ning.http.client.AsyncHttpClientConfig.Builder
import play.api.libs.iteratee.Iteratee
import play.api.libs.iteratee.Execution.Implicits.defaultExecutionContext
import play.api.libs.ws.ning.NingWSClient
import scala.util.{Success,Failure}

object Client {
 val client = new NingWSClient(new Builder().build())
 def print = Iteratee.foreach { chunk: Array[Byte] => println(new String(chunk)) }

 def main(args: Array[String]) {
   connect()
   def connect(): Unit = {
     val consumer = client.url("http://streaming.resource.com")
     consumer.get(_ => print).onComplete {
       case Success(s) => println("Success")
       case Failure(f) => println("Recursive retry"); connect()
     }
   }
 }
}



<在我已经共享的示例中, get [A](...)方法返回 Future [Iteratee [Array [Byte] ,A]] 。上述文章的作者我已经包括了说,scala.concurrent期货不会合并一旦他们回来,但Twitter的未来一些如何管理这一点。我使用的PlayFramework实现,但是,它使用由标准Scala 2.1X库提供的期货。

In the example I've shared, the get[A](...) method returns a Future[Iteratee[Array[Byte],A]]. The author of the above article I've included remarks that "scala.concurrent Futures don't get merged" once they return but that Twitter's futures some how manage this. I'm using the PlayFramework implementation, however, which uses futures provided by the standard Scala 2.1X library.

你有任何人有证据支持或驳回这些声明吗?

Do any of you have evidence that support or dismiss these claims? Does my code pose a memory leak?

推荐答案

您链接的问题(在评论中,不是问题或答案)到发生与 flatMap 的内存泄漏。你的代码不使用 flatMap ,所以我不认为你不会遇到任何问题,因为你只是有条件地执行另一个未来通过回调,而不是关心以前的。

The issue you linked (was in a comment, not the question or answer) refers to a memory leak that occurred with flatMap. Your code doesn't use flatMap, so I don't think you wouldn't run into any problems, as you're just conditionally executing another Future via a callback, and not caring at all about the previous.

无论如何,它是不相干的,因为这个问题在2.10 .3。请参见问题 SI-7336 pull request 来修复它。更多信息。

Either way, it's kind of irrelevant because this issue was fixed in 2.10.3. See issue SI-7336 and the pull request that fixes it for more info.

这篇关于当递归调用Future [T]中的函数时,如何缓解内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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