Created
January 30, 2015 16:48
-
-
Save imhoffd/42e5bf9f41a35aa32270 to your computer and use it in GitHub Desktop.
threading in scala with 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 scala.util.{Success, Failure} | |
import scala.concurrent._ | |
import ExecutionContext.Implicits.global | |
import duration._ | |
class Thing { | |
private var _a = 0 | |
def a = { | |
Thread.sleep(500L) | |
_a | |
// uncomment the following line to see other behavior | |
// throw new RuntimeException("um, something happened") | |
} | |
def a_=(v: Int) = _a = v | |
} | |
object Threading1 { | |
def main(args: Array[String]) { | |
val t = new Thing() | |
val f: Future[Int] = future { | |
t.a // reference to something outside this future. cool! | |
} | |
t.a = 1 | |
f onComplete { | |
case Success(value) => println("I have a thing: " + value) | |
case Failure(e: RuntimeException) => t.a = 0 // Await.result rethrows exceptions thrown | |
case Failure(e) => println("something really weird happened") | |
} | |
println("doing something else now") | |
t.a = 2 | |
// the state of this object kind of scares me | |
// uncomment the following line to see what I mean | |
// Await.ready(f, 60.seconds) | |
t.a = 3 | |
val result = Await.result(f, 60.seconds) | |
println("doing more stuff right now because I have a thing: " + result) | |
} | |
} | |
object Threading2 { | |
def main(args: Array[String]) { | |
val tasks: Seq[Future[Int]] = for (i <- 1 to 100) yield future { | |
println("Executing task " + i) | |
Thread.sleep(1000L) // Doing work | |
i * i | |
} | |
val aggregated: Future[Seq[Int]] = Future.sequence(tasks) | |
val squares: Seq[Int] = Await.result(aggregated, 15.seconds) | |
println("Squares: " + squares) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment