【问题标题】:How do I guarantee that I am using not the default/global implicit context如何保证我使用的不是默认/全局隐式上下文
【发布时间】:2018-02-11 15:49:14
【问题描述】:

我有一个包含此导入的 scala 文件

import scala.concurrent.ExecutionContext.Implicits.global

这很好用,因为我正在使用的 Future 在该文件中的方法中运行良好。但是,我创建了一个单独的方法用于磁盘 IO,并且我有一个新的执行上下文。我希望这个方法使用这个上下文,而其他方法可以继续使用默认上下文。我怎么保证?我目前这样做如下

private def testContext():Future[Int] = { val system = ActorSystem.create() implicit val myexecutionContext = system.dispatchers.lookup("blocking-io-dispatcher.db-backup-context") Future{logger.error("inside my new thread pool wonderland");10}{myexecutionContext}

有没有办法在每次 Future 调用结束时不指定这样的“myexecutionContext”,我可以让这个方法仍然对所有 Future 调用使用“myexecutionContext”?简而言之,我不想在我的“testContext”方法中一次又一次地指定“myexecutionContext”作为参数。我该怎么做?

【问题讨论】:

    标签: scala akka future


    【解决方案1】:

    您无需在testContext() 中指定myexecutionContextmyexecutionContexttestContext() 内部定义,它优先于在方法外部导入的global 上下文。在testContext() 中创建的所有Futures 将默认使用myexecutionContext

    【讨论】:

    • 这是因为我在我的方法中将其声明为“隐式”吗?如果我将myexecutionContext 声明为val .. 而不是implicit val 会怎样。还有一种方法可以验证哪个池用于执行Future 只是为了让我自己满意?
    • 您需要将其声明为implicit val,才能将其用作隐式参数。否则将使用全局的。验证请看这个问题:stackoverflow.com/questions/38517712/…
    • 是的,感谢您的帮助,我刚刚做了同样的Thread.currentThread.getName,就像我们在 Java 中所做的一样,我得到了我的上下文的名称。最后一个问题是为什么它在我的日志中前面加上“默认”这个词。这是我在日志中看到的inside my new thread pool wonderland and context is default-blocking-io-dispatcher.db-backup-context-7
    • 我对 Akka 调度器不是很熟悉,可能涉及到一些未定义的东西(也许blocking-io-dispatcher 不存在?)但这只是一个疯狂的猜测。
    • 我正在使用 play 并在 application.conf blocking-io-dispatcher { db-backup-context { thread-pool-executor { core-pool-size-factor = 10.0 core-pool-size-max = 10 } } 中创建它
    猜你喜欢
    • 1970-01-01
    • 2017-01-09
    • 2021-08-04
    • 2014-09-26
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    • 2018-09-08
    • 2022-01-11
    相关资源
    最近更新 更多