scala thread multithreading parallelism

Concurrency in Scala is carried out using Future which is an abstraction over Java Threads. It lets us use multithreading without dealing with the internal low level details.

A Future runs the blocking code in off main thread. It provides various methods such as:

  1. onComplete
  2. map
  3. andThen etc

which let’s use threading effectively.

  def longRunningTaskFuture: Future[Int] = Future {
    Thread.sleep(5_000)
    12
  }
 
  val future = longRunningTaskFuture
  println(future)
  future.onComplete((`try`: Try[Int]) => {
    `try` match
      case Success(value) => println(value)
      case Failure(s) => s.printStackTrace()
  })

References

  1. Concurrency Scala book 3
  2. Future and Promises