gpt4 book ai didi

scala - 多个 onCompletion 在 Scala 的 Futures 中起作用

转载 作者:行者123 更新时间:2023-12-01 08:24:19 25 4
gpt4 key购买 nike

在 Scala 中试验 Futures 时,我注意到多次调用 OnCompletion 是有效的!

问题 1 - 显然,我不应该这样编写代码,但我想知道在这种情况下编译器是否应该引发错误?

import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Failure,Success}

object ConcurrencyExample extends App {
val time = System.currentTimeMillis()

println("looking at inventory")
//create code we want to execute concurrently
val f: Future[Int] = Future //or just f = Future
{
println("add item to shopping basket")
Thread.sleep(30) //simulate backend process delay
println("Item added")
1 //simulate the no. of items in basket

}

//this works
f onComplete (x => println("on complete1 " + x))
//and this too
f onComplete {
case Success(value) => println("on complete2 size of basket" + value)
case Failure(e) => println(e)
}

//this is called as well though I do not see problem in this as I can segregate the code for completion, success and failure
f onSuccess {
case v => println("on success size of basket"+v)
}

f onFailure {
case e => println("on failure. Reason"+e)
}


for (i<- 1 to 5)
{
println("looking at more items in inventory ")
Thread.sleep(10)
}
Thread.sleep(500)
}

//结果

looking at inventory
add item to shopping basket
looking at more items in inventory
Item added
on success size of basket1
**on complete2 size of basket1
on complete1 Success(1)**
looking at more items in inventory
looking at more items in inventory
looking at more items in inventory
looking at more items in inventory

问题 2 - 多个回调(相同类型)的执行顺序是否确定?

最佳答案

文档中的下一个引用可能会回答您的两个问题:

The onComplete, onSuccess, and onFailure methods have result type Unit, which means invocations of these methods cannot be chained. Note that this design is intentional, to avoid suggesting that chained invocations may imply an ordering on the execution of the registered callbacks (callbacks registered on the same future are unordered).

a1:您可以注册任意数量的回调

a2:它们将按“随机”顺序执行。

关于scala - 多个 onCompletion 在 Scala 的 Futures 中起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41359952/

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