在Scala中阻止调用的期货 [英] Futures for blocking calls in Scala

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

问题描述

Akka 文档说:


您可能会试图封装阻塞调用但是这个策略太简单了:当应用程序在负载增加的情况下运行时,很有可能发现瓶颈或内存或线程用完。
you may be tempted to just wrap the blocking call inside a Future and work with that instead, but this strategy is too simple: you are quite likely to find bottlenecks or run out of memory or threads when the application runs under increased load.

他们建议采用以下策略:

They suggest the following strategies:


  • 未来中进行阻塞调用,确保在任何时间点的此类调用的数量的上限(提交无界的多个此类性质的任务将耗尽您的内存或线程限制)。

  • Do the blocking call within a Future, ensuring an upper bound on the number of such calls at any point in time (submitting an unbounded number of tasks of this nature will exhaust your memory or thread limits).

Future

您知道吗?任何执行这些战略?

Do you know about any implementation of those strategies?

推荐答案

期货在执行上下文。这从 Future API中是显而易见的:涉及附加一些回调到未来或从任意计算或从另一个未来构建未来的任何调用需要隐式可用 ExecutionContext 对象。因此,您可以通过调整它们运行的​​ ExecutionContext 来控制您的期货的并发设置。

Futures are run within execution contexts. This is obvious from the Future API: any call which involves attaching some callbacks to a future or to build a future from an arbitrary computation or from another future requires an implicitly available ExecutionContext object. So you can control the concurrency setup for your futures by tuning the ExecutionContext in which they run.

要实现第二个策略,你可以做类似

For instance, to implement the second strategy you can do something like

import scala.concurrent.ExecutionContext
import java.util.concurrent.Executors
import scala.concurrent.future

object Main extends App {

  val ThreadCount = 10
  implicit val executionContext = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(ThreadCount))

  val f = future {
    println(s"Hello ! I'm running in an execution context with $ThreadCount threads")
  }

}

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

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