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

标签 scala

在 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/

相关文章:

json - 从 JSON 文件中提取子对象(作为 JSON)

scala - Scala中枚举子类的字段

scala - 在 Scala 中使用 Recovery 组合 Futures

Scala:确定用于泛型的方法结果类型

performance - Spark 最近 30 天过滤器,提高性能的最佳方法

Scala 防止混合的方法

scala - 在 Scala 中,检查数组是否单调的功能方法是什么?

c# - 为什么具体化的泛型很难与更高级的类型结合使用?

scala - 如何获得 Scala 2.10 反射引用的实际对象?

scala - 在 `DataFrame` 、 `RDD` 之间相互转换对性能有何影响?