I have the following code in 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.")
My intent here is to parallelize heatWaterFor(...)
and boilMilkFor(...)
as they are independent. But I feel that the above code is sequential and doesn't harness the power of futures at all. Apparently, it takes 3000 milliseconds to run (which is an additional proof).
What is the fundamental thing I'm missing here?