Last active
July 16, 2016 15:48
-
-
Save Krasnyanskiy/7938a44dd23fd7dc0377b6cc60391a87 to your computer and use it in GitHub Desktop.
-scala: combine futures
This file contains hidden or 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 java.lang.System.currentTimeMillis | |
import java.util.concurrent.TimeUnit.{MILLISECONDS, SECONDS} | |
import java.util.concurrent.{TimeUnit, Executors} | |
import java.util.concurrent.Executors.newFixedThreadPool | |
import scala.concurrent.ExecutionContext.fromExecutorService | |
import scala.concurrent.{Future, ExecutionContext} | |
import scala.util.{Failure, Success} | |
/** | |
* @author Alexander Krasniansky | |
*/ | |
object FutureApp extends App { | |
val executor = newFixedThreadPool(8) | |
implicit val executionContext = fromExecutorService(executor) | |
val start = currentTimeMillis() | |
val f0: Future[Int] = Future { Thread.sleep(2700); 0 } | |
val f1: Future[Int] = Future { Thread.sleep(5500); 1 } | |
val f2: Future[Int] = Future { Thread.sleep(1500); 2 } | |
val seq: Future[List[Int]] = Future.sequence(f0 :: f1 :: f2 :: Nil) | |
seq onComplete { | |
case Success(res) => println { "R:" + res } | |
case Failure(t) => println { "R:" + t.getMessage } | |
} | |
if (!executionContext.awaitTermination(5500, MILLISECONDS)) { | |
val end = currentTimeMillis() | |
println { s"executionTime=${(end - start).toDouble / 1000}" } | |
executionContext.shutdownNow() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
or
or