【发布时间】:2019-08-31 12:42:19
【问题描述】:
我最近开始研究 Scala,并发现了它的一个名为 Future 的特性。我发布了一个问题以寻求有关我的代码的帮助以及一些帮助。
在那次谈话中,有人告诉我不建议从 Future 中检索值。
我知道执行时它是一个并行过程,但如果不建议检索 Future 的值,我如何/何时访问它的结果?如果 Future 的目的是运行独立于主线程的线程/进程,为什么不建议访问它? Future 会自动将其输出分配给它的调用者吗?如果是这样,我们怎么知道何时访问它?
我编写了以下代码以返回带有 Map[String, String] 的 Future。
def getBounds(incLogIdMap:scala.collection.mutable.Map[String, String]): Future[scala.collection.mutable.Map[String, String]] = Future {
var boundsMap = scala.collection.mutable.Map[String, String]()
incLogIdMap.keys.foreach(table => if(!incLogIdMap(table).contains("INVALID")) {
val minMax = s"select max(cast(to_char(update_tms,'yyyyddmmhhmmss') as bigint)) maxTms, min(cast(to_char(update_tms,'yyyyddmmhhmmss') as bigint)) minTms from queue.${table} where key_ids in (${incLogIdMap(table)})"
val boundsDF = spark.read.format("jdbc").option("url", commonParams.getGpConUrl()).option("dbtable", s"(${minMax}) as ctids")
.option("user", commonParams.getGpUserName()).option("password", commonParams.getGpPwd()).load()
val maxTms = boundsDF.select("minTms").head.getLong(0).toString + "," + boundsDF.select("maxTms").head.getLong(0).toString
boundsMap += (table -> maxTms)
}
)
boundsMap
}
如果我必须使用 getBounds 方法返回的值,我可以通过以下方式访问它吗?
val tmsobj = new MinMaxVals(spark, commonParams)
tmsobj.getBounds(incLogIds) onComplete ({
case Success(Map) => val boundsMap = tmsobj.getBounds(incLogIds)
case Failure(value) => println("Future failed..")
})
有人能解开我的疑惑吗?
【问题讨论】:
-
boundsMap既是var又是可变集合?这是不必要的多余。 -
@jwh,那么我该如何构建“成功”的案例。因为它说“Pattern type is in compatible with the expected type, found: mutable.map.type, required mutable.Map{String,String]”
-
你错过了我评论的重点。请参阅我发布的答案。