运维开发网

斯卡拉期货基础知识

运维开发网 https://www.qedev.com 2020-07-14 10:51 出处:网络 作者:运维开发网整理
我在 Scala中有以下代码: case class Water(temp: Int) case class Milk(temp: Int) def heatWaterFor(minutes: Int, water: Water) = Future { Thread.sleep(1000) Water(82) } def boilMilkFor(minutes: Int, milk:
我在 Scala中有以下代码:

case class Water(temp: Int)

case class Milk(temp: Int)

def heatWaterFor(minutes: Int, water: Water) = Future {
  Thread.sleep(1000)
  Water(82)
}

def boilMilkFor(minutes: Int, milk: Milk) = Future {
  Thread.sleep(1000)
  Milk(90)
}

def frothMilk(hotwater: Water, hotmilk: Milk) = Future {
  Thread.sleep(1000)
  hotmilk
}

val start = System.currentTimeMillis()

val milkMaker = for {
   water <- heatWaterFor(10, Water(10))
   milk <- boilMilkFor(5, Milk(10))
   frothed = frothMilk(water, milk)
   hotMilk <- frothed
 } yield (hotMilk)

Await.ready(milkMaker, Duration.Inf)
val end = System.currentTimeMillis() - start
println(milkMaker.value + " , Time taken: "+((end/1000))+" seconds.")

我的目的是将heatWaterFor(…)和boilMilkFor(…)并行化,因为它们是独立的.但我觉得上面的代码是连续的,根本没有利用期货的力量.显然,运行需要3000毫秒(这是一个额外的证据).

我在这里缺少什么基本的东西?

for表达式被简化为一系列map,flatMap和withFilter操作.您具体的表达式减少到这样:

heatWaterFor(10, Water(10))
        .flatMap(water => boilMilkFor(5, Milk(10))
                             .flatMap(milk => frothMilk(water, milk))

正如您在此处所看到的,下一个未来的执行是在上一个完成时开始的.因此,如果要并行执行它们,则需要执行以下操作:

val heatWater = heatWaterFor(10, Water(10))
val boilMilk = boilMilkFor(5, Milk(10))

val milkMaker = for {
   water <- heatWater
   milk <- boilMilk
   hotMilk <- frothMilk(water, milk)
} yield (hotMilk)

这将同时启动heatWaterFor和boilMilkFor,然后在这两个完成时启动frothMilk(因为它取决于其他两个期货的结果).

0

精彩评论

暂无评论...
验证码 换一张
取 消