Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement