Advertisement
Guest User

Scala_MultiThreading

a guest
Jan 13th, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.93 KB | None | 0 0
  1. import scala.concurrent.{Await, ExecutionContext, Future}
  2. import scala.concurrent.duration._
  3.  
  4. // No @volatile or `synchronized`
  5. class Foo {
  6.   private var _id: Option[String] = None
  7.  
  8.   def set(id: String): Unit = {
  9.     _id = Option(id)
  10.   }
  11.   def unset(): Unit = {
  12.     _id = None
  13.   }
  14.   def get: Option[String] = {
  15.     _id
  16.   }
  17. }
  18.  
  19. object Test {
  20.   val arr = Array[Foo](new Foo, new Foo)
  21.   implicit val ex: ExecutionContext = scala.concurrent.ExecutionContext.Implicits.global
  22.  
  23.   def main(args: Array[String]): Unit = {
  24.     val f = Future {
  25.       println(s"Thread[${Thread.currentThread.getId}]: set to 0")
  26.       arr(0).set("0")
  27.     }
  28.     .map { _ =>
  29.       val p = arr(0).get
  30.       println(s"Thread[${Thread.currentThread.getId}]: get ${p}")
  31.     }
  32.     .map { _ =>
  33.       println(s"Thread[${Thread.currentThread.getId}]: unset")
  34.       arr(0).unset
  35.     }
  36.  
  37.     val res = Await.result(f, 100.seconds)
  38.     println(res)
  39.   }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement