Advertisement
Guest User

Untitled

a guest
Jan 30th, 2015
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. import scala.util.{Success, Failure}
  2. import scala.concurrent._
  3. import ExecutionContext.Implicits.global
  4. import duration._
  5.  
  6. class Thing {
  7. private var _a = 0
  8.  
  9. def a = {
  10. Thread.sleep(500L)
  11. _a
  12. // uncomment the following line to see other behavior
  13. // throw new RuntimeException("um, something happened")
  14. }
  15.  
  16. def a_=(v: Int) = _a = v
  17. }
  18.  
  19. object Threading1 {
  20. def main(args: Array[String]) {
  21. val t = new Thing()
  22. val f: Future[Int] = future {
  23. t.a // reference to something outside this future. cool!
  24. }
  25. t.a = 1
  26. f onComplete {
  27. case Success(value) => println("I have a thing: " + value)
  28. case Failure(e: RuntimeException) => t.a = 0 // Await.result rethrows exceptions thrown
  29. case Failure(e) => println("something really weird happened")
  30. }
  31. println("doing something else now")
  32. t.a = 2
  33. // the state of this object kind of scares me
  34. // uncomment the following line to see what I mean
  35. // Await.ready(f, 60.seconds)
  36. t.a = 3
  37. val result = Await.result(f, 60.seconds)
  38. println("doing more stuff right now because I have a thing: " + result)
  39. }
  40. }
  41.  
  42. object Threading2 {
  43. def main(args: Array[String]) {
  44. val tasks: Seq[Future[Int]] = for (i <- 1 to 100) yield future {
  45. println("Executing task " + i)
  46. Thread.sleep(1000L) // Doing work
  47. i * i
  48. }
  49.  
  50. val aggregated: Future[Seq[Int]] = Future.sequence(tasks)
  51.  
  52. val squares: Seq[Int] = Await.result(aggregated, 15.seconds)
  53. println("Squares: " + squares)
  54. }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement