gpt4 book ai didi

Scala future 超时奇怪的行为

转载 作者:行者123 更新时间:2023-12-04 08:44:06 25 4
gpt4 key购买 nike

这是示例代码 scala 2.13.3:

import scala.concurrent.{ExecutionContext}

val scheduller: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor()

val promise = Promise[A]()
scheduller.schedule(
new Runnable {
override def run(): Unit = {
promise.failure(new TimeoutException)
scheduller.shutdown()
}
},
500,
TimeUnit.MILLISECONDS
)
Future.firstCompletedOf(Seq(INF_FUTURE, promise.future))
如果 INF_FUTURE = Future.never,超时将起作用但如果 INF_FUTURE = Future {while (true) {}} 执行不会停止
你能解释一下这里发生了什么吗?

最佳答案

那是因为你用了singleThreadScheduledExecutor .我假设您创建了 ExecutionContext来自 scheduller :

val scheduller: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor()
implicit val ec: ExecutionContextExecutor = scala.concurrent.ExecutionContext.fromExecutorService(scheduller)

val promise = Promise[Int]()
scheduller.schedule(
new Runnable {
override def run(): Unit = {
promise.failure(new TimeoutException)
scheduller.shutdown()
}
},
500,
TimeUnit.MILLISECONDS
)
如果您仅使用一个执行程序创建执行上下文,您的程序将在 while (true) 内评估同步和卡住。环形。
如果您将切换到全局执行上下文,问题将被忽略(如果您的机器有多个内核):
implicit val ec: ExecutionContextExecutor = scala.concurrent.ExecutionContext.global
Future.never 的情况下如果你会像这样等待结果:
Await.result(Future.firstCompletedOf(Seq(INF_FUTURE, promise.future)).map {
x =>
println(x)
}, 10.seconds)
你会得到异常:

Exception in thread "main"java.util.concurrent.RejectedExecutionException: Taskjava.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask@eb88a9dfrejected fromjava.util.concurrent.ScheduledThreadPoolExecutor@e24c7ced[Shuttingdown, pool size = 1, active threads = 1, queued tasks = 0, completedtasks = 1]


这会告诉您线程池大小的问题。
所以,您对 Future.never 没有任何问题因为你没有等待它的结果。

关于Scala future 超时奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64418140/

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