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:
onComplete
map
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()
})