斯卡拉期货基础知识

时间:2015-08-27 07:16:51

标签: scala asynchronous concurrency promise future

我在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毫秒(这是一个额外的证据)。

我在这里缺少的基本要素是什么?

0 个答案:

没有答案