Created
May 16, 2013 21:02
-
-
Save emiaj/5595076 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object HelloFuturesScala extends App { | |
import scala.concurrent._ | |
import scala.concurrent.duration._ | |
import ExecutionContext.Implicits.global | |
def identityFunction(number:Int) = { | |
Thread.sleep(3000) | |
number | |
} | |
println("Hello Futures Scala") | |
def run(number:() => Int) = { | |
val startTime = System.currentTimeMillis | |
val value = number(); | |
val elapsedTime = ((System.currentTimeMillis - startTime) / 1000.0) | |
println("------------------------------") | |
println("Value is " + value + " calculated in " + elapsedTime + " seconds") | |
println("------------------------------") | |
} | |
println("Blocking version") | |
run(()=>{ | |
val number1 = identityFunction(1) | |
val number2 = identityFunction(2) | |
val number3 = identityFunction(3) | |
number1 + number2 + number3 | |
}) | |
println("Non-Blocking version") | |
run(()=>{ | |
val number1 = future { identityFunction(1) } | |
val number2 = future { identityFunction(2) } | |
val number3 = future { identityFunction(3) } | |
val sum = for{ | |
x <- number1 | |
y <- number2 | |
z <- number3 | |
} yield (x + y + z) | |
Await.result(sum,Duration.Inf) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment