Created
October 29, 2014 09:22
-
-
Save javierfs89/249540d4d8e1cfdd3dc2 to your computer and use it in GitHub Desktop.
Sync Futures vs Async Futures
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
import scala.concurrent._ | |
import scala.concurrent.duration._ | |
import ExecutionContext.Implicits.global | |
object MyApp { | |
def processA(f: Int, b: Int, c: Int) = { | |
Thread.sleep(2000) | |
f + b + c | |
} | |
def processB(g: Int) = { | |
Thread.sleep(2000) | |
g | |
} | |
def processC(d: Int, e: Int) = { | |
Thread.sleep(2000) | |
d + e | |
} | |
def processD = { | |
Thread.sleep(2000) | |
5 | |
} | |
def processE = { | |
Thread.sleep(2000) | |
10 | |
} | |
def processF = { | |
Thread.sleep(2000) | |
15 | |
} | |
def processG = { | |
Thread.sleep(2000) | |
20 | |
} | |
def runAllAsync = { | |
val startTime = System.currentTimeMillis() | |
val futureD = Future { processD } | |
val futureE = Future { processE } | |
val futureF = Future { processF } | |
val futureG = Future { processG } | |
val futureB = for { | |
g <- futureG | |
} yield(processB(g)) | |
val futureC = for { | |
d <- futureD | |
e <- futureE | |
} yield(processC(d, e)) | |
val futureA = for { | |
f <- futureF | |
b <- futureB | |
c <- futureC | |
} yield(processA(f, b, c)) | |
val result = Await.result(futureA, 7 seconds) | |
println(s"Time: ${System.currentTimeMillis() - startTime}") | |
result | |
} | |
def runAllSync = { | |
val startTime = System.currentTimeMillis() | |
val futureA = for { | |
f <- Future { processF } | |
g <- Future { processG } | |
b <- Future { processB(g) } | |
d <- Future { processD } | |
e <- Future { processE } | |
c <- Future { processC(d, e) } | |
} yield(processA(f, b, c)) | |
val result = Await.result(futureA, 15 seconds) | |
println(s"Time: ${System.currentTimeMillis() - startTime}") | |
result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment