Skip to content

Instantly share code, notes, and snippets.

@emiaj
Created May 16, 2013 21:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emiaj/5595076 to your computer and use it in GitHub Desktop.
Save emiaj/5595076 to your computer and use it in GitHub Desktop.
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