Created
March 12, 2015 14:03
-
-
Save shsdev/488b89a22103b2dccab5 to your computer and use it in GitHub Desktop.
Use execution context to execute concurrent processes using futures. Number of threads is defined in a fixed thread pool. Blocking for a maximum number of minutes, see http://docs.scala-lang.org/style/naming-conventions.html for non-blocking alternative.
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 java.util.concurrent.Executors | |
import scala.concurrent.Await | |
import scala.concurrent.ExecutionContext | |
import scala.concurrent.Future | |
import scala.concurrent.duration.DurationInt | |
/** | |
* Use execution context to execute concurrent processes using futures. | |
* Number of threads is defined in a fixed thread pool. | |
* Blocking for a maximum number of minutes, see http://docs.scala-lang.org/style/naming-conventions.html | |
* for non-blocking alternative. | |
*/ | |
object ConcurrentExecutionUsingFutures extends App { | |
val NumThreads = 4 | |
val MaxWaitMinutes = 1 | |
implicit val ec = ExecutionContext.fromExecutorService(Executors.newFixedThreadPool(NumThreads)) | |
val t0 = System.currentTimeMillis() | |
/** | |
* Double letter and wait for 2 seconds | |
*/ | |
def getDoubled(letter: String): String = { | |
val t1 = System.currentTimeMillis() | |
println("letter: " + letter + " (elapsed: "+(t1-t0)+")" + ", thread-name: "+Thread.currentThread().getName()) | |
Thread.sleep(2000) | |
letter+letter | |
} | |
val alphabet = List( | |
"a", "b", "c", "d", | |
"e", "f", "g", "h", | |
"i", "j", "k", "l", | |
"m", "n", "o", "p", | |
"q", "r", "s", "t", | |
"u", "v", "w", "x", | |
"y", "z") | |
val fResult = for(letter <- alphabet) yield Future { getDoubled(letter) } | |
// blocking | |
val result: List[String] = Await.result(Future.sequence(fResult.toList), MaxWaitMinutes minutes) | |
for(res <- result) { | |
println(res) | |
} | |
ec.shutdown() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment