gpt4 book ai didi

scala - 我应该阻止 future - scala

转载 作者:行者123 更新时间:2023-12-01 08:29:37 40 4
gpt4 key购买 nike

根据 Scala 文档,不应在 Future 上进行阻塞。

“正如前面提到的,为了性能和防止死锁,强烈建议不要阻塞 future 。 future 的回调和组合器是使用其结果的首选方式。但是,在某些情况下,阻塞可能是必要的,并且得到支持通过 Futures 和 Promises API。”

如何确保在我的程序退出之前我的所有 future 都已完成(并且它们的回调已完成)?我通常在 main 函数的末尾使用 Await.result 来确保所有 Futures 都已完成。

object ConcurrencyExample extends App {
val gpf= Future {some operations}
val ccf = Future{some operations}


val atbf = for {g <- gpf
c <- ccf if c == true} yield {some operations}

//is it OK to use Await? If not, how do I ensure that all Futures have finished
?
Await.result(atbf,1000 millis )
}

问题
  • 使用 Await 是错误的吗?我的代码不等待 future 完成否则
  • 如果是这样,替代方案是什么?
  • 如何确保 Future 及其回调在我的主程序退出之前已完成?
  • 最佳答案

    是的,您可以 Await.result在你的情况下。

    You can use Await.result for keeping main thread alive for futures to complete



    小心 Await.result

    请注意,这适用于 Akka 和 play 应用程序

    Await.result should be used very carefully only when it is absolutely necessary.


    Await.result阻塞它正在运行的线程,直到给定的持续时间。阻塞线程将浪费宝贵的计算资源,因为该线程将无法进行任何有用的计算,例如处理新请求或算法中的数字运算等。

    所以,避免使用 Await.result越多越好。

    But, when do we use it (Await.result) ?



    这是使用 Await.result 的典型用例之一.

    假设您编写了一个包含主线程的程序,并且主线程内的所有计算都是异步的。现在,一旦您在主线程内开始异步计算。有些人必须停止存在的主线程,直到异步计算完成,否则程序停止运行并且您看不到异步计算的结果。

    When an application begins running, there is one non-daemon thread, whose job is to execute main(). JVM will not exit by itself until and unless non-daemon threads are completed.


    object Main {
    def main(args: Array[String]): Unit = {
    import scala.concurrent.Future
    import scala.concurrent.duration._

    val f = Future { //do something }
    //stop main thread till f completes
    Await.result(f, 10 seconds)
    }
    }

    Future uses daemon threads for running. So daemon threads cannot stop the JVM from shutting down. So JVM shuts down even if non-daemon threads are running.



    在上述情况下,没有其他方法可以停止(阻塞)主线程,直到计算 f如果不是主线程退出并且计算停止,则完成。

    In most of the cases you do not need to use Await.result and simple Future composition using map and flatMap would suffice.



    使用 Await.result 的风险(一般都是阻塞代码)

    Running out of threads in event based model



    在基于事件的模型中,如果您有需要很长时间返回的阻塞代码,您将很快耗尽线程。在 playframework 中,任何阻塞调用都可能降低应用程序的性能,并且应用程序会因为线程用完而变得非常缓慢。

    Running out of memory in non-event based models



    在每个请求模型的线程中。当您遇到需要很长时间退出/返回的阻塞调用时。

    情况 1:如果您有固定的线程池,那么应用程序可能会耗尽线程。

    情况 2:如果您有动态增长的线程池,那么您的应用程序将遭受过多的上下文切换开销,并且还会因为内存中的阻塞线程过多而耗尽内存。

    在所有情况下,除了等待某些 IO 或某些其他事件之外,没有做任何有用的工作。

    关于scala - 我应该阻止 future - scala,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41381626/

    40 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com